代码之家  ›  专栏  ›  技术社区  ›  DooDoo

获取具有外部程序集自定义属性的所有属性

  •  1
  • DooDoo  · 技术社区  · 1 年前

    我读过的主题:

    How to get a list of properties with a given attribute?

    Reflection - get attribute name and value on property


    我创建了一个外部程序集(类库),并在其中定义了一个类和一个自定义属性:

    namespace ClassLibrary1
    {
        public class MyCustomAttribute:Attribute
        {
            public string Message { get; set; }
        }
    
        public class Class1
        {
            public int MyProperty0 { get; set; }
    
            [MyCustom(Message ="aaa")]
            public int MyProperty1 { get; set; }
    
            [MyCustom(Message = "bbb")]
            public int MyProperty2 { get; set; }
        
            public int MyProperty3 { get; set; }
        }
    }
    

    对于第一个目标,我想获得所有房产 MyCustomAttribute 对于 Class1 我写了这段代码:

    Assembly assembly = Assembly.LoadFile(<file path>);
    var props = assembly.GetType("ClassLibrary1.Class1").GetProperties().Where(
    prop => Attribute.IsDefined(prop, typeof(ClassLibrary1.MyCustomAttribute)));
    

    但它回来了 null 对于 props 。我这样更改了代码:

    PropertyInfo[] props = assembly.GetType("ClassLibrary1.Class1").GetProperties();
    foreach (PropertyInfo prop in props)
    {
        object[] attrs = prop.GetCustomAttributes(false);
        foreach (object attr in attrs)
        {
            var authAttr = attr as ClassLibrary1.MyCustomAttribute; <--------
            if (authAttr != null)
            {
                string propName = prop.Name;
                string message = authAttr.Message;
    
                Console.WriteLine($"{propName} ... {message }");
            }
        }
    }
    

    但返回了指定的行 无效的 对于 attr 但它实际上是一种 ClassLibrary1.MyCustomAttribute :

    Get all properties with a custom attribute for external assembly

    null

    我弄不明白是什么问题。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Sweeper    1 年前

    显然,类型名称 ClassLibrary1.MyCustomAttribute 在您的代码中,即使它们具有相同的命名空间和简单名称,也不表示与您加载的程序集中声明的类型相同的类型。

    您将使用以下命令获得正确的类型 assembly.GetType ,以同样的方式你得到 Type 代表 Class1 .

    var props = assembly.GetType("ClassLibrary1.Class1").GetProperties().Where(
        prop => Attribute.IsDefined(prop, assembly.GetType("ClassLibrary1.MyCustomAttribute"))
    );
    

    得到 Message 使用反射,

    var attributeType = assembly.GetType("ClassLibrary1.MyCustomAttribute");
    var messageProperty = attributeType.GetProperty("Message");
    object[] attrs = prop.GetCustomAttributes(false);
    foreach (object attr in attrs)
    {
        if (attributeType.IsInstanceOfType(attr))
        {
            string propName = prop.Name;
            string message = messageProperty.GetValue(attr);
    
            Console.WriteLine($"{propName} ... {message }");
        }
    }
    
    推荐文章