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

标签 .net xamarin portable-class-library

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

我已经更新了我的解决方案以开始使用 .NET 4.6。我的一个 PCL 项目对枚举做了一些反射(reflection)。我已经更新了 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 平台。

如有任何想法,我们将不胜感激。

最佳答案

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

但是上面的评论给我指明了正确的方向,一个大问题是它试图给我类(主要枚举)的属性而不是枚举元素本身。上面评论中的链接让我在第一行代码中使用了 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();
}

关于.net - 缺少 Type.GetMember 和 MemberInfo.GetCustomAttributes (C# PCL .NET 4.6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292548/

相关文章:

c# - Mono 和 appdomain 安全/权限集

c# - CS0117 C# 'Resource.Id' 不包含 "PhoneNumberText"的定义

c# - HttpWebRequest.Headers[HttpRequestHeader.Referer] 因错误而失败

.net - 将PCL转换为常规类库

c# - 在可移植类库中包含 XPathSelectElement

c# - 如何在不将图像大小存储在数据库中的情况下在asp repeater中动态更改图像大小

c# - 如何从 .NetStandard 类库中引用 net40 框架程序集?

c# - 可以通过 SSL 通过 WCF 使用 Kerberos token 配置文件吗?

c# - MVVMCross ValueConverter Bool 到 MvxColor/Color

c# - 从 Xamarin 可移植类库发送 Http 请求