我不太确定如何很好地提出这个问题。抱歉,如果不清楚。我正在尝试确定对象所充当的类型,而不是对象的实际类型。
说我有这两个类:
public class A{
public A() {
string thisTypeName = this.GetType().???; // the value I'm looking for here is "A" not "B"
}
}
public class B : A { }
Run Code Online (Sandbox Code Playgroud)
我不想要的是...
string thisTypeName = this.GetType().BaseType.Name;
Run Code Online (Sandbox Code Playgroud)
......因为如果我决定这样做......
public class C : B { }
Run Code Online (Sandbox Code Playgroud)
...那么现在我的 this.GetType().BaseType 将引用类 B,而不是 A。
有没有内置的方法来做到这一点?我猜我可以在 Type 上写一个扩展方法来做我想做的事。
用你现在得到的一些建议来观看它。其中一些在我的书中有点臭。
你想使用:
typeof(A).IsAssigneableFrom(aninstance.GetType());
Run Code Online (Sandbox Code Playgroud)
确定一个类型是从基类型派生的,还是实现了一个接口
请参阅:http : //msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx。这个页面有很多有趣的例子,展示了它支持的所有微妙案例
| 归档时间: |
|
| 查看次数: |
12389 次 |
| 最近记录: |