当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# Type.IsAssignableFrom(Type)用法及代码示例


Type.IsAssignableFrom(Type)方法用于确定是否可以将指定类型的实例分配给当前类型的变量。

用法: public virtual bool IsAssignableFrom (Type c);
Here, it takes the type to compare with the current type.

返回值:如果满足以下任一条件,则此方法返回true:


  • c和当前实例代表相同的类型。
  • c是从当前实例直接或间接派生的。如果c从当前实例继承,则直接从当前实例派生;如果c继承自从当前实例继承的一个或多个类的继承,则c是从当前实例间接派生的。
  • 当前实例是c实现的接口。
  • c是泛型类型参数,当前实例表示c的约束之一。

以下示例程序旨在说明Type.IsAssignableFrom()方法的使用:

示例1:

// C# program to demonstrate the 
// Type.IsAssignableFrom() Method 
using System; 
using System.Globalization; 
using System.Reflection; 
using System.IO; 
  
// Defining MyClass extended 
// from TypeDelegator 
public class MyClass : TypeDelegator { } 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        // Declaring and initializing object of Type 
        Type objType = typeof(TypeDelegator); 
  
        // Getting array of Properties by 
        // using GetProperties() Method 
        bool status = objType.IsAssignableFrom(typeof(MyClass)); 
  
        // Display the Result 
        if (status) 
            Console.WriteLine("Instance of a specified type can be "
                   + "assigned to a variable of the current type."); 
        else
            Console.WriteLine("Instance of a specified type can't be "
                     + "assigned to a variable of the current type."); 
    } 
}
输出:
Instance of a specified type can be assigned to a variable of the current type.

示例2:

// C# program to demonstrate the 
// Type.IsAssignableFrom() Method 
using System; 
using System.Globalization; 
using System.Reflection; 
using System.IO; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        // Declaring and initializing object of Type 
        Type objType = typeof(double); 
  
        // Getting array of Properties by 
        // using GetProperties() Method 
        bool status = objType.IsAssignableFrom(typeof(int)); 
  
        // Display the Result 
        if (status) 
            Console.WriteLine("Instance of a specified type can be "
                   + "assigned to a variable of the current type."); 
        else
            Console.WriteLine("Instance of a specified type can't be "
                     + "assigned to a variable of the current type."); 
    } 
}
输出:
Instance of a specified type can't be assigned to a variable of the current type.

参考:



相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 C# | Type.IsAssignableFrom(Type) Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。