Type.GetMember & MemberInfo.GetCustomAttributes 缺失(C# PCL .NET 4.6)
Type.GetMember & MemberInfo.GetCustomAttributes missing (C# PCL .NET 4.6)
我可能真的很愚蠢。
我已经更新了我的解决方案以开始使用 .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 平台
如有任何想法,我们将不胜感激。
好的,所以这花了一段时间(甚至忘了这是个问题!!)
但是上面的评论给我指出了正确的方向,一个大问题是它试图给我 Class(主要枚举)的属性而不是枚举元素本身。上面评论中的 link 让我在第一行代码中使用 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 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 平台如有任何想法,我们将不胜感激。
好的,所以这花了一段时间(甚至忘了这是个问题!!)
但是上面的评论给我指出了正确的方向,一个大问题是它试图给我 Class(主要枚举)的属性而不是枚举元素本身。上面评论中的 link 让我在第一行代码中使用 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();
}