繁体   English   中英

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

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

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

例子:

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
}

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

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) ,即使所讨论的变量被声明为对A的引用。

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

GetType总是返回实际实例化的类型。 即最衍生的类型。 这意味着您的GetSubType的行为就像GetType本身一样,因此是不必要的。

要静态获取某种类型的类型信息,您可以使用typeof(MyClass)

您的代码有一个错误: System.Attribute.GetCustomAttributes返回Attribute[]而不是Type

GetType 始终返回实际类型。

其原因在.NET框架和CLR很深,因为 JIT 和 CLR 使用.GetType方法在内存中创建一个保存对象信息的 Type 对象,所有对对象的访问和编译都是通过这个类型实例。

有关详细信息,请参阅 Microsoft Press 的“CLR via C#”一书。

输出:

 GetType: Parent: 'Playground.ParentClass' Child: 'Playground.ChildClass' Child as Parent: 'Playground.ChildClass' GetParentType: Parent: 'Playground.ParentClass' Child: 'Playground.ParentClass' Child as Parent: 'Playground.ParentClass'

程序.cs:

using Playground;

var parent = new ParentClass();
var child = new ChildClass();
var childAsParent = child as ParentClass;

Console.WriteLine("GetType:\n" +
                  $"\tParent: '{parent.GetType()}'\n" +
                  $"\tChild: '{child.GetType()}'\n" +
                  $"\tChild as Parent: '{childAsParent.GetType()}'\n");

Console.WriteLine("GetParentType:\n" +
                  $"\tParent: '{parent.GetParentType()}'\n" +
                  $"\tChild: '{child.GetParentType()}'\n" +
                  $"\tChild as Parent: '{childAsParent.GetParentType()}'\n");

子类.cs

namespace Playground
{
    public class ChildClass : ParentClass
    {
    }
}

父类.cs

namespace Playground
{
    public class ParentClass
    {
        public Type GetParentType()
        {
            return typeof(ParentClass);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM