Topics I’ve read:
How to get a list of properties with a given attribute?
Reflection – get attribute name and value on property
I created an external assembly(Class Library) and I defined a class and a custom attribute in it:
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; }
}
}
For first goal I want to get all properties with MyCustomAttribute
for Class1
and I wrote this code:
Assembly assembly = Assembly.LoadFile(<file path>);
var props = assembly.GetType("ClassLibrary1.Class1").GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(ClassLibrary1.MyCustomAttribute)));
but it returned null
for props
. I changed the code this way:
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 }");
}
}
}
but the specified line returned null
for attr
. but it actually is type of ClassLibrary1.MyCustomAttribute
:
I can’t figure out what is the problem.
5
Evidently, the type name ClassLibrary1.MyCustomAttribute
in your code does not represent the same type as declared in the assembly you loaded, even if they have the same namespace and simple name.
You will get the correct type using assembly.GetType
, in the same way you get the Type
representing Class1
.
var props = assembly.GetType("ClassLibrary1.Class1").GetProperties().Where(
prop => Attribute.IsDefined(prop, assembly.GetType("ClassLibrary1.MyCustomAttribute"))
);
To get Message
, use reflection,
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 }");
}
}