【问题标题】:Is GetFields supported in a PCL?PCL 中是否支持 GetFields?
【发布时间】: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));
}     

【问题讨论】:

标签: c# .net-4.5 portable-class-library


【解决方案1】:

要添加 Damien 的答案,在 .Net for Windows Store Apps 中,您可以使用以下扩展方法:

using System.Reflection;

var fields = type.GetRuntimeFields();

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

这似乎相当于 .Net Framework 的 GetFields 方法。

此方法返回在指定类型上定义的所有字段, 包括继承、非公共、实例和静态字段。

【讨论】:

    【解决方案2】:

    仅仅因为一个方法说它在可移植类库中受支持并不意味着它支持所有可能的目标。如果您查看Type class 的帮助,它会列出每个成员并显示每个受支持系统的图标。

    在这种情况下,您会注意到 GetFields 旁边没有绿色购物袋图标 - Windows 应用商店应用程序支持它,因此只要您将 Windows 应用商店包含在您的PCL 支持的目标集,它将不可用。

    另一种说法是 - 在方法的版本信息块中,如果 Windows Store 支持它们,则会有一个特定的部分说明它。比较GetGenericTypeDefinition

    .NET 框架
    支持:4.5、4、3.5、3.0、2.0
    .NET Framework 客户端配置文件
    支持:4、3.5 SP1
    可移植类库
    支持:便携式类库
    .NET for Windows Store 应用程序
    支持:Windows 8

    GetFields

    .NET 框架
    支持:4.5、4、3.5、3.0、2.0、1.1、1.0
    .NET Framework 客户端配置文件
    支持:4、3.5 SP1
    可移植类库
    支持:可移植类库

    对于 Windows 应用商店应用,为了进行反射,您应该改用 TypeInfo 类 - 但请注意,它仍然不特别支持 GetFields 方法。

    【讨论】:

    • 感谢您的详细解释......这解决了正在发生的事情的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多