从基类调用时会的GetType()返回最派生类型? [英] Will GetType() return the most derived type when called from the base class?
本文介绍了从基类调用时会的GetType()返回最派生类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
威尔的GetType()从基类调用时返回最派生类型
例如:
公共抽象类的一个
{
私有类型的GetInfo()
{
返回System.Attribute.GetCustomAttributes(this.GetType()) ;
}
}
公共B类:A
{
//字段在这里有添加到它们
一些自定义属性}
或者我应该只是使派生类必须实现象下面的抽象方法?
公共抽象类的一个
{
保护的抽象类型GetSubType();
私有类型的GetInfo()
{
返回System.Attribute.GetCustomAttributes(GetSubType());
}
}
公共B类:A
{
//字段在这里有添加到他们一些自定义属性
保护类型GetSubType()
{
返回的GetType();
}
}
解决方案
的GetType()
将返回实际,实例化的类型。在你的情况,如果你调用的GetType()
在 B
的一个实例,它将返回 typeof运算(b)
,即使有问题的变量声明为一个参考 A
。
有没有理由对你的 GetSubType()
方法。
Will GetType() return the most derived type when called from the base class?
Example:
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()
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
.
There is no reason for your GetSubType()
method.
这篇关于从基类调用时会的GetType()返回最派生类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文