缺少Type.GetMember和MemberInfo.GetCustomAttributes(C#PCL .NET 4.6)

Dav*_*ton 3 .net portable-class-library xamarin

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

我已经更新了解决方案,可以开始使用.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();
Run Code Online (Sandbox Code Playgroud)

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

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

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

任何想法将不胜感激。

Dav*_*ton 5

好,所以花了一段时间(忘了甚至是个问题!!)

但是,以上注释为我指明了正确的方向,但有一个大问题,那就是它试图为我提供类(主枚举)的属性,而不是枚举元素本身。上面注释中的链接将我带到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();
}
Run Code Online (Sandbox Code Playgroud)