This article introduces a general method for dynamically accessing and extracting property values of a class.
Define a common method that accepts type parameters:
public string GetDomainName()
]
Inside the method:
Use typeof(T).GetCustomAttributes
to retrieve custom attributes:
var dnAttribute = typeof(T).GetCustomAttributes(
typeof(DomainNameAttribute), true
).FirstOrDefault() as DomainNameAttribute;
If the property exists, its value is returned:
if (dnAttribute != null)
{
return dnAttribute.Name;
}
Otherwise, return null:
return null;
]
For broader applicability, generalize this method to handle any attribute:
public static class AttributeExtensions
{
public static TValue GetAttributeValue(
this Type type,
Func valueSelector)
where TAttribute : Attribute
}
Inside the extension method:
Retrieve custom properties:
var att = type.GetCustomAttributes(
typeof(TAttribute), true
).FirstOrDefault() as TAttribute;
If the attribute exists, use the provided valueSelector
to extract the required value:
if (att != null)
{
return valueSelector(att);
}
Otherwise, return the default value of this type:
return default(TValue);
]
DomainName
attribute of MyClass
: string name = typeof(MyClass).GetDomainName();
MyClass
using the extension method: string name = typeof(MyClass)
.GetAttributeValue((DomainNameAttribute dna) => dna.Name);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3