📜  C#| Type.IsAssignableFrom(Type)方法

📅  最后修改于: 2021-05-29 18:00:27             🧑  作者: Mango

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

下面的程序说明了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.

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.type.isassignablefrom?view=netframework-4.8