我在这里可能真的很愚蠢。
我已经更新了我的解决方案以开始使用 .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/