c# – GetFields是否支持PCL?

前端之家收集整理的这篇文章主要介绍了c# – GetFields是否支持PCL?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图实现一个在 https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Enumeration.cs发现的枚举类.

在下面的代码中,我收到一个编译错误,GetFields无法解析.

  1. public static IEnumerable<T> GetAll<T>() where T : Enumeration
  2. {
  3. var type = typeof(T);
  4. var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
  5.  
  6. return fields.Select(info => info.GetValue(null)).OfType<T>();
  7. }

根据http://msdn.microsoft.com/en-us/library/ch9714z3(v=vs.110).aspx,便携式类库支持方法.

我的图书馆针对Windows商店应用程序.NET Framework 4.5和Windows Phone 8.

有什么想法在这里发生了什么?

  1. public static IEnumerable<T> GetAll<T>() where T : Enumeration
  2. {
  3. var type = typeof(T);
  4. var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
  5.  
  6. return fields.Select(info => info.GetValue(null)).OfType<T>();
  7. }
  8.  
  9. public static IEnumerable GetAll(Type type)
  10. {
  11. var fields = type.GetRuntimeFields().Where(x => x.IsPublic || x.IsStatic);
  12.  
  13. return fields.Select(info => info.GetValue(null));
  14. }

解决方法

添加到Damien的答案,在.Net中的Windows Store Apps,您可以使用以下扩展方法
  1. using System.Reflection;
  2.  
  3. var fields = type.GetRuntimeFields();

http://msdn.microsoft.com/en-us/library/system.reflection.runtimereflectionextensions.getruntimefields.aspx

这似乎与.NET Framework的GetFields方法相当.

This method returns all fields that are defined on the specified type,including inherited,non-public,instance,and static fields.

猜你在找的C#相关文章