sh0*_*ged 16 .net c# reflection type-systems system.type
请考虑以下代码:
public class A
{
}
public class B : A
{
}
public class C : B
{
}
class D
{
public static bool IsDescendantOf(this System.Type thisType, System.Type thatType)
{
/// ???
}
void Main()
{
A cValue = new C();
C.GetType().IsDescendantOf(cValue.GetType());
}
}
Run Code Online (Sandbox Code Playgroud)
实施IsDescendantOf的最佳方法是什么?
我意识到这并没有直接回答你的问题,但你可能会考虑使用它而不是你的例子中的方法:
public static bool IsDescendantOf<T>(this object o)
{
if(o == null) throw new ArgumentNullException();
return typeof(T).IsSubclassOf(o.GetType());
}
Run Code Online (Sandbox Code Playgroud)
所以你可以像这样使用它:
C c = new C();
c.IsDescendantOf<A>();
Run Code Online (Sandbox Code Playgroud)
另外,要回答关于Type.IsSubclassOf和Type.IsAssignableFrom之间差异的问题 - IsAssignableFrom在某种意义上是较弱的,如果你有两个对象a和b,这是有效的:
a = b;
Run Code Online (Sandbox Code Playgroud)
那typeof(A).IsAssignableFrom(b.GetType())
是真的 - 所以a可以是b的子类,或者是接口类型.
相反,a.GetType().IsSubclassOf(typeof(B))
如果a是b的子类,则只返回true.鉴于你的扩展方法的名称,我会说你应该使用IsSubclassOf代替IsAssignable;
归档时间: |
|
查看次数: |
8113 次 |
最近记录: |