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

当从基类调用时,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();
}
}
53955 次浏览

GetType()将返回实际的实例化类型。在您的示例中,如果对 B的实例调用 GetType(),它将返回 typeof(B),即使所涉及的变量被声明为对 A的引用。

没有理由使用 GetSubType()方法。

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

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

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

GetType 始终返回实际类型。

其原因深藏在 .NET框架和 CLR中,因为 JIT 和 CLR 使用 .GetType方法在内存中创建一个 Type 对象,该对象保存对象的信息,所有对该对象的访问和编译都是通过这个 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'

程序:

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");

儿童课堂

namespace Playground
{
public class ChildClass : ParentClass
{
}
}

家长课堂

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