簡體   English   中英

如何檢查類型參數是否實際上是一個接口

[英]How to check whether a type parameter is actually an interface

我有一個泛型函數,我想檢查類型參數是否是一個接口。 反正有嗎? 提前致謝!

使用TypeIsInterface屬性..

public void DoCoolStuff<T>()
{
    if(typeof(T).IsInterface)
    {
        //TODO: Cool stuff...
    }
}

如果要約束泛型方法,以便type參數只能是實現某個特定接口的類型,那么您應該執行以下操作:

void YourGenericMethod<T>() where T : IYourInterface {
    // Do stuff. T is IYourInterface.
}

您可以使用typeof運算符和Type.IsInterface屬性顯式檢查泛型類型參數。

void MyMethod<T>() {
  bool isInterface = typeof(T).IsInterface;
}

暫無
暫無

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

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