[英]How to find out if a class is an instance of a generic interface in C#?
那么是否有可能獲得Property<T>
為Property
的實例,並且不知道其通用T
類型參數而調用其方法?
private interface Property<T>
{
T Value { get;}
void DestroyEarth();
}
class MyProperty : Property<int>
{
public int Value{ get { return 1 }; }
public void DestroyEarth() { }
}
所以我想知道是否可以通過類似方法接收MyProperty實例上的DestroyEarth()
void PropertyCaller(Property p){p.DestroyEarth();}
(注意:我們沒有定義或沒有簡單的Property
類或接口)
編輯:
使用問題編輯,我會說:聲明一個非通用接口,並移動與T
不相關的方法,例如:
interface IProperty {
object Value { get;}
void DestroyEarth();
}
interface IProperty<T> : IProperty {
new T Value { get;}
}
class MyProperty : IProperty<int>
{
object IProperty.Value { get { return Value; } }
public int Value{get {return 1;} }
public void DestroyEarth(){}
}
當您不知道T
時,只需針對IProperty
進行編碼。
(與發布代碼之前的答案不同,它在歷史記錄中 ,僅供參考)
然后您有:
void PropertyCaller(IProperty p) { p.DestroyEarth(); }
當然,您也可以讓編譯器找出T
:
void PropertyCaller<T>(IProperty<T> p) { p.DestroyEarth(); }
您要的是在您不知道T並且仍想以某種方式調用該實例的情況下,在Property<T>
類型與Property<object>
之間自動轉換(我想)。 出於各種原因,這是無法做到的(在通用類型中研究“協方差/反方差”,以便對問題空間有所了解)。
我建議您自己進行此轉換,並在具有相同簽名但將T編寫為對象的Property<T>
類的頂部實現IProperty
(非通用-請參見Marc的答案)接口。 然后在需要時通過強制轉換將調用重定向到T方法。
無論T
為何,您的Property
類都應具有一些實現,而Property<T>
從Property
派生的,更多實現與T
有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.