[英]C# casting generic parameter to interface
我需要幫助將通用的paremetrs轉換為接口。
我有這樣的預烘焙代碼:
public interface InterFoo<T> {...}
public InterFoo<T> specialFoo<T>() where T : InterFoo<T> {...}
public InterFoo<T> regularFoo<T>() {...}
我想實現這樣的東西
public InterFoo<T> adaptiveFoo<T>()
{
if (T is InterFoo<T>)
return specialFoo<T as InterFoo>();
return regularFoo<T>();
}
在這一點上,我無法找到任何解決方案,所以任何事情都會有所幫助,謝謝。
編輯:最初函數返回了一個int但是有一個更簡單的解決方案與代碼的預期目的不兼容,函數已被更改為請求泛型類型。
is
和as
運算符只編譯編譯器知道的類型可以為null
(可空值類型或引用類型)。
您可以嘗試調用IsAssignableFrom:
public int adaptiveFoo<T>()
{
if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
return specialFoo<InterFoo>();
return regularFoo<T>();
}
**更新以反映問題的變化**
不幸的是,類型約束是病毒式的,為了使您的方法能夠編譯(當保持編譯器的嚴格類型檢查時),您還需要將約束添加到此方法中。 但是,反思可以規避這種限制:
你的方法是:
public InterFoo<T> adaptiveFoo<T>()
{
if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
{
var method = typeof (Class1).GetMethod("specialFoo");
var genericMethod = method.MakeGenericMethod(typeof(T));
return (Interfoo<T>)method.Invoke(this, null);
}
return regularFoo<T>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.