我有一個Constraints
對象,它會得到一套其他對象必須遵守的規則。如何從反映的上下文中調用泛型方法?
constraints
有一個方法稱爲GetEnumValueRange<T>()
其中T
是一種枚舉。
因此,舉例來說,我能有一個枚舉定義爲:
[Flags]
public enum BoxWithAHook
{
None = 0,
Thing1 = 1,
Thing2 = 2,
...
// lots of other things that might be in the box
ThingN = N
}
然後我可以得到一個範圍,其在給定範圍內有效值:
var val = constraints.GetEnumValueRange<BoxWithAHook>();
問題是我正在嘗試使用反射來完成這項工作。我無法指定類型爲,因爲它可以是延伸Enum
的任何內容。這是我的一個例子:
if (propertyInfo.PropertyType.BaseType == typeof(Enum))
{
var val = constraints.GetEnumValueRange<>(); // what is the generic type here?
// now I can use val to get the constraint values
}
我可以指定泛型類型嗎?理想情況下,這會工作:
constraints.GetEnumValueRange<propertyInfo.PropertyType>();
,但它顯然不會
如果你必須**調用一個通用的方法,那麼Andrei是正確的,但是請注意,如果你正在做很多事情,這種反射會損害性能。如果你是,有一些方法可以優化這個。不過,僅僅爲了一個電話就不值得。 Lukazoid是正確的,如果你**正在使用反射,那麼基於泛型的API將會是一個痛苦。事實上,我重新編寫了一個大型庫的整個核心,將通用'Foo(...)'方法改爲'Foo(Type type,...)'方法。現在對結果感到高興。 –
2012-08-08 11:46:28