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

本文标题为:从基类调用时,GetType() 会返回派生最多的类型吗?

基础教程推荐