从基类调用时,GetType() 会返回派生最多的类型吗?

Will GetType() return the most derived type when called from the base class?(从基类调用时,GetType() 会返回派生最多的类型吗?)
本文介绍了从基类调用时,GetType() 会返回派生最多的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GetType() 从基类调用时会返回派生最多的类型吗?

Will GetType() return the most derived type when called from the base class?

例子:

public abstract class A
{
    private Type GetInfo()
    {
         return System.Attribute.GetCustomAttributes(this.GetType());
    }
}

public class B : A
{
   //Fields here have some custom attributes added to them
}

或者我应该只创建一个派生类必须实现的抽象方法,如下所示?

Or should I just make an abstract method that the derived classes will have to implement like the following?

public abstract class A
{
    protected abstract Type GetSubType();

    private Type GetInfo()
    {
         return System.Attribute.GetCustomAttributes(GetSubType());
    }
}

public class B : A
{
   //Fields here have some custom attributes added to them

   protected Type GetSubType()
   {
       return GetType();
   }
}

推荐答案

GetType() 将返回实际的实例化类型.在您的情况下,如果您在 B 的实例上调用 GetType(),它将返回 typeof(B),即使在question 被声明为对 A 的引用.

GetType() will return the actual, instantiated type. In your case, if you call GetType() on an instance of B, it will return typeof(B), even if the variable in question is declared as a reference to an A.

您的 GetSubType() 方法没有理由.

There is no reason for your GetSubType() method.

这篇关于从基类调用时,GetType() 会返回派生最多的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)
6