Fei*_*ngo 115 c# polymorphism inheritance
从基类调用时,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
}
Run Code Online (Sandbox Code Playgroud)
或者我应该创建一个抽象方法,派生类必须实现如下所示?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 129
GetType()将返回实际的实例化类型.在你的情况下,如果你调用GetType()一个实例B,它将返回typeof(B),即使有问题的变量被声明为对它的引用A.
你的GetSubType()方法没有理由.
Cod*_*aos 22
GetType始终返回实际实例化的类型.即最衍生的类型.这意味着你的GetSubType行为就像GetType自己一样,因此是不必要的.
要静态获取您可以使用的某种类型的类型信息typeof(MyClass).
你的代码有一个错误:不System.Attribute.GetCustomAttributes返回.Attribute[]Type