我確實有很多靜態類表示不同模塊中的不同狀態。但是他們共享提取其信息的常用算法。替代:靜態類作爲通用參數
public static class Constants
{
public static readonly int A = 0;
}
所以現在我有,這是否每個類多個靜態功能。它們僅在處理的靜態類的類型(及其全名)方面有所不同。
public static SelectListItem getConstantsSelectListItem()
{ // pseudo example
return new SelectListItem { Text = "A" , Value = Constants.A };
}
要刪除當前和避免未來的codebloat,我想對靜態類使用反射。這裏是我的方法,這將做的工作(如果有可能):
public static ReturnType getProperties<T>()
{ // basically same logic as getConstantsSelectListItem
var propertyList = typeof(T) .GetFields(BindingFlags.Public | BindingFlags.Static).ToList();
foreach(var item in propertyList)
{
var curConstant = (int)(item.GetValue(null));
// do some work here..
}
}
var constantsProperties = getProperties<Constants>();
的錯誤是:
static types cannot be used as argument types
我已閱讀,對於仿製藥僅實例(因此沒有靜態類)可以使用。
什麼是做出類似工作的好方法?
可能重複[C# - 靜態類型不能用作類型參數](http://stackoverflow.com/questions/5858591/c-sharp-static-types-cannot-be-used-as-type-arguments ) – C1sc0