【发布时间】:2013-10-22 08:02:17
【问题描述】:
我正在尝试实现在https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Enumeration.cs 找到的枚举类。
在下面的代码中,我收到了一个无法解析GetFields 的编译错误。
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var type = typeof(T);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
return fields.Select(info => info.GetValue(null)).OfType<T>();
}
根据http://msdn.microsoft.com/en-us/library/ch9714z3(v=vs.110).aspx,可移植类库支持此方法。
我的库面向 Windows 应用商店应用程序、.NET Framework 4.5 和 Windows Phone 8 的 .NET。
知道这里发生了什么吗?
解决方案
public static IEnumerable<T> GetAll<T>() where T : Enumeration
{
var type = typeof(T);
var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
return fields.Select(info => info.GetValue(null)).OfType<T>();
}
public static IEnumerable GetAll(Type type)
{
var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
return fields.Select(info => info.GetValue(null));
}
【问题讨论】:
-
有关这里发生的事情以及原因的一些详细信息,请参阅此答案:stackoverflow.com/a/14063316/1509
标签: c# .net-4.5 portable-class-library