相关疑难解决方法(0)

检查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的最佳方法是什么?

.net c# reflection type-systems system.type

16
推荐指数
3
解决办法
8113
查看次数

如何判断实例是某个类型还是任何派生类型

我正在尝试编写验证来检查Object实例是否可以转换为变量Type.我有一个Type实例,用于他们需要提供的对象类型.但类型可能会有所不同.这基本上就是我想要做的.

        Object obj = new object();
        Type typ = typeof(string); //just a sample, really typ is a variable

        if(obj is typ) //this is wrong "is" does not work like this
        {
            //do something
        }
Run Code Online (Sandbox Code Playgroud)

类型对象本身具有IsSubClassOf和IsInstanceOfType方法.但我真正想要检查的是objtyp的实例还是从typ派生的任何类.

看起来像一个简单的问题,但我似乎无法弄明白.

c# types casting

14
推荐指数
3
解决办法
1万
查看次数

标签 统计

c# ×2

.net ×1

casting ×1

reflection ×1

system.type ×1

type-systems ×1

types ×1