【发布时间】:2015-10-12 09:56:10
【问题描述】:
我确实有很多静态类,它们代表不同模块中的不同状态。但是,它们共享提取其信息的通用算法。
public static class Constants
{
public static readonly int A = 0;
}
所以现在我为每个类都有多个执行此操作的静态函数。它们仅在处理的静态类的类型(及其整体名称)上有所不同。
public static SelectListItem getConstantsSelectListItem()
{ // pseudo example
return new SelectListItem { Text = "A" , Value = Constants.A };
}
为了删除当前代码并避免将来出现代码膨胀,我想对静态类使用反射。这是我的方法,可以完成这项工作(如果可能的话):
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# reflection static-classes