【问题标题】:Custom Class Attributes in Metro Style AppMetro Style App 中的自定义类属性
【发布时间】:2012-05-09 13:06:29
【问题描述】:

我正在尝试在 Metro Style App 可移植库中定义和检索类的自定义属性。

类似

[AttributeUsage(AttributeTargets.Class)]
public class FooAttribute : Attribute
{
}

[Foo]
public class Bar
{
}


class Program
{
    static void Main(string[] args)
    {
        var attrs = CustomAttributeExtensions.GetCustomAttribute<FooAttribute>(typeof(Bar));
    }
}

这在普通 4.5 中有效,但在针对 Metro 风格应用程序的便携式库中它告诉我

Cannot convert type 'System.Type' to 'System.Reflection.MemberInfo'

谢谢

【问题讨论】:

  • 显然,你需要做 var attrs = CustomAttributeExtensions.GetCustomAttribute(typeof(Bar).GetTypeInfo());
  • @user1364325 如果您上面评论中的代码解决了问题,请将其发布为答案并将其标记为已回答。

标签: c# windows-runtime custom-attributes system.reflection portable-class-library


【解决方案1】:

根据 OP:

你需要做 var attrs = CustomAttributeExtensions.GetCustomAttribute(typeof(Bar).GetTypeIn‌​fo());

这似乎与the documentation一致

【讨论】:

    【解决方案2】:

    或者,也可以按原样利用扩展:

    var attr = typeof(Bar).GetTypeInfo().GetCustomAttribute<FooAttribute>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 2013-03-17
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多