2012-08-08 45 views
1

我有一個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>(); 

,但它顯然不會

+0

如果你必須**調用一個通用的方法,那麼Andrei是正確的,但是請注意,如果你正在做很多事情,這種反射會損害性能。如果你是,有一些方法可以優化這個。不過,僅僅爲了一個電話就不值得。 Lukazoid是正確的,如果你**正在使用反射,那麼基於泛型的API將會是一個痛苦。事實上,我重新編寫了一個大型庫的整個核心,將通用'Foo (...)'方法改爲'Foo(Type type,...)'方法。現在對結果感到高興。 – 2012-08-08 11:46:28

回答

2

您可能需要通過MethodInfo反射的一點點位置:

if (propertyInfo.PropertyType.BaseType == typeof(Enum)) 
{ 
    MethodInfo method = typeof(Constraints).GetMethod("GetEnumValueRange"); 
    MethodInfo genericMethod = method.MakeGenericMethod(propertyInfo.PropertyType); 
    var val = genericMethod.Invoke(constraints, null); 

    // ... 
} 
1

爲什麼不把的GetEnumValueRange一個重載需要一個Type參數,所以你最終得到類似這樣的結果:

public class Constraints 
{ 
    public IEnumerable GetEnumValueRange(Type enumType) 
    { 
     // Logic here 
    } 

    public IEnumerable<T> GetEnumValueRange<T>() 
    { 
     return GetEnumValueRange(typeof(T)).Cast<T>(); 
    } 
} 

然後,你可以簡單地使用constraints.GetEnumValueRange(propertyInfo.PropertyType),我會親自避免反思,如果有這樣的可用替代方案。