Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在UWP中获取内容属性的名称?_C#_.net_Reflection_Uwp - Fatal编程技术网

C# 如何在UWP中获取内容属性的名称?

C# 如何在UWP中获取内容属性的名称?,c#,.net,reflection,uwp,C#,.net,Reflection,Uwp,我试过了 public string GetContentProperty(Type type) { var contentPropertyAttribute = type.GetTypeInfo().GetCustomAttribute<ContentPropertyAttribute>(); return contentPropertyAttribute?.Name; } 公共字符串GetContentProperty(类型) { var contentPr

我试过了

public string GetContentProperty(Type type)
{
     var contentPropertyAttribute = type.GetTypeInfo().GetCustomAttribute<ContentPropertyAttribute>();
     return contentPropertyAttribute?.Name;
}
公共字符串GetContentProperty(类型)
{
var contentPropertyAttribute=type.GetTypeInfo().GetCustomAttribute();
返回contentPropertyAttribute?.Name;
}
但它总是返回null


在WPF中,它可以正常工作。

我已经研究这个问题超过了我真正应该看到的时间,但仍然不知道完整的答案。我真诚地希望有其他人来提供更好的选择

到目前为止,我发现在UWP上,调用
GetCustomAttributes()
返回一个空枚举。起初我认为这可能与UWP程序集的类型剥离有关,但我可以在调试构建中重现该问题,而不启用“使用.NET本机工具链编译”选项,因此编译的程序集应该包含完整的类型信息。即使我修改了
Default.rd.xml
文件以包含
(理论上可能省略了
ContentPropertyAttribute
类型),也没有什么帮助

所以,我不知道到底发生了什么。但是,在此期间,您的方法的一个版本将起作用:

static string GetContentProperty<TSource>()
{
    return typeof(TSource).GetTypeInfo().CustomAttributes
        .Where(a => a.AttributeType == typeof(ContentPropertyAttribute))
        .FirstOrDefault()?.NamedArguments.Cast<CustomAttributeNamedArgument?>()
        .Where(n => n.Value.MemberName == "Name")
        .FirstOrDefault()?.TypedValue.Value.ToString();
}
静态字符串GetContentProperty()
{
返回typeof(TSource).GetTypeInfo().CustomAttributes
.其中(a=>a.AttributeType==typeof(ContentPropertyAttribute))
.FirstOrDefault()?.NamedArguments.Cast()
.Where(n=>n.Value.MemberName==“Name”)
.FirstOrDefault()?.TypedValue.Value.ToString();
}
(我没有将
Type
对象传入,而是将其设置为泛型,让该方法完成查找类型的工作。)

在上面,我将
CustomAttributeNamedArgument
值类型转换为可为空的类型,这样我就可以使用
FirstOrDefault()
,这比具体化枚举、检查其长度、然后检索第一个非空元素更方便

即使使用
GetCustomAttributes()
方法,这种方法仍然可以工作,这一事实使我认为这与已编译的UWP程序集丢弃类型信息的行为有某种关联。但不幸的是,我对UWP的这一特定领域知之甚少,不知道该怎么做

我会第一个同意,上述不是一个非常好的选择。必须获取属性的声明信息而不是属性本身,然后在该数据中搜索属性名称,最后必须将非类型化的值属性从数据转换回
字符串
,以便可以返回,这是非常混乱和不理想的


但它确实有效。那么,就是这样。:)

我把它放在标题中:)无论如何,我将删除WPF标记以避免混淆try
IntrospectionExtensions.GetTypeInfo(type).GetCustomAttribute()