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.
參考:
相關用法
- C# DateTimeOffset.Add()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# Math.Sin()用法及代碼示例
- C# Math.Cos()用法及代碼示例
- C# Dictionary.Add()用法及代碼示例
- C# Math.Tan()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 C# | Type.IsAssignableFrom(Type) Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。