簡體   English   中英

如何找出(Type是Type)C#

[英]How to find out if (Type is Type) C#

我正在使用兩種類型,一種是通用的,另一種不是。 我沒有對象的實例,但我想if ( MyType is T )還是換句話說if ( MyType inherits T)

我再次尋找:

if ( Truck is Vehicle )

if ( MyTruckObject is Vehicle)

嘗試:

if (typeof(Truck).IsSubclassOf(typeof(Vehicle)))

好吧,給定泛型類型參數,您可以執行以下操作:

if (typeof(Vehicle).IsAssignableFrom(typeof(T))) 
{

}

或者,將約束應用於方法以確保它:

public void DoSomething<T>() where T : Vehicle 
{

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM