[英]“this” keyword type when called on an object of derived class from base class
[英]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: 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.