在 C# 中动态访问类属性
在运行时访问类属性是动态检索元数据或配置信息的强大技术。 这可以使用 C# 的反射功能来实现。
检索特定属性(DomainNameAttribute):
通用方法 GetDomainName<T>
简化了从任何类检索 DomainNameAttribute
的过程:
public string GetDomainName<T>() { var dnAttribute = typeof(T).GetCustomAttributes(typeof(DomainNameAttribute), true) .FirstOrDefault() as DomainNameAttribute; return dnAttribute?.Name; }
使用示例:
// Returns "MyTable" (assuming myclass has the attribute) string domainName = GetDomainName<myclass>();
属性访问的更通用方法:
为了更广泛的适用性,更通用的扩展方法允许检索任何属性类型及其特定属性:
public static class AttributeExtensions { public static TValue GetAttributeValue<TAttribute, TValue>( this Type type, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { var attribute = type.GetCustomAttributes(typeof(TAttribute), true) .FirstOrDefault() as TAttribute; return attribute != null ? valueSelector(attribute) : default(TValue); } }
使用示例:
string name = typeof(MyClass).GetAttributeValue((DomainNameAttribute dna) => dna.Name);
此方法采用属性类型和 lambda 表达式来从属性实例中选择所需的属性值。 这为访问各种属性属性提供了灵活性。
以上是如何在 C# 中在运行时读取类属性?的详细内容。更多信息请关注PHP中文网其他相关文章!