【问题标题】:Type.GetMember & MemberInfo.GetCustomAttributes missing (C# PCL .NET 4.6)缺少 Type.GetMember 和 MemberInfo.GetCustomAttributes (C# PCL .NET 4.6)
【发布时间】:2015-12-15 15:04:32
【问题描述】:

我可能在这里真的很愚蠢。

我已经更新了开始使用 .NET 4.6 的解决方案。我的一个 PCL 项目对枚举进行了一些反思。我更新了 PCL 兼容性,并修复了它创建的空 project.json 文件。但是,此 PCL 项目不再构建,因为它无法识别 Type.GetMember()MemberInfo[x].GetCustomAttribute(...)

我一直在使用并且一直工作到今天的代码是:

        MemberInfo[] info = e.GetType().GetMember(e.ToString());
        if (info != null && info.Length > 0)
        {
            object[] attributes = info[0].GetCustomAttributes(typeof(Description), false);
            if (attributes != null && attributes.Length > 0)
                return ((Description)attributes[0]).Text;
        }

        return e.ToString();

该项目仅引用以下路径中的 .NET 库:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETPortable\v4.5\Profile\Profile7\

作为 PCL 配置的一部分,该项目也自动支持 Xamarin 平台。

任何想法将不胜感激。

【问题讨论】:

  • 是配置文件 78 吗?见stackoverflow.com/questions/19741631/…
  • @Jason 这只是配置文件 7 - 但我认为无论如何这可能会解决问题。需要做更多的测试才能确定,但​​至少现在可以构建了:)

标签: .net xamarin portable-class-library


【解决方案1】:

好的,所以这需要一段时间(甚至忘记了它甚至是一个问题!)

但是,上面的 cmets 为我指明了正确的方向,其中一个大问题是它试图为我提供类(主枚举)的属性,而不是枚举元素本身。上面评论中的链接让我在第一行代码中使用了GetTypeInfo,这必须替换为GetRuntimeField

一个小的调整意味着我最终得到了以下几点:

public static string ToDescription(this ArtistConnection e)
{
    var info = e.GetType().GetRuntimeField(e.ToString());
    if (info != null)
    {
        var attributes = info.GetCustomAttributes(typeof(Description), false);
        if (attributes != null)
        {
            foreach (Attribute item in attributes)
            {
                if (item is Description)
                    return (item as Description).Text;
            }
        }
    }

    return e.ToString();
}

【讨论】:

  • 感谢大卫发帖,真的帮了我大忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
相关资源
最近更新 更多