我有办法访问C#类属性吗?
例如,如果我有以下类:
...
[TableName("my_table_name")]
public class MyClass
{
...
}
我可以这样做:
MyClass.Attribute.TableName => my_table_name
谢谢!
答案 0 :(得分:5)
您可以使用反射来获取它。这是一个完整的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class TableNameAttribute : Attribute
{
public TableNameAttribute(string tableName)
{
this.TableName = tableName;
}
public string TableName { get; set; }
}
[TableName("my_table_name")]
public class SomePoco
{
public string FirstName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var classInstance = new SomePoco() { FirstName = "Bob" };
var tableNameAttribute = classInstance.GetType().GetCustomAttributes(true).Where(a => a.GetType() == typeof(TableNameAttribute)).Select(a =>
{
return a as TableNameAttribute;
}).FirstOrDefault();
Console.WriteLine(tableNameAttribute != null ? tableNameAttribute.TableName : "null");
Console.ReadKey(true);
}
}
}
答案 1 :(得分:2)
这是一个扩展程序,通过扩展对象为您提供属性帮助程序,可以更轻松。
namespace System
{
public static class ReflectionExtensions
{
public static T GetAttribute<T>(this object classInstance) where T : class
{
return ReflectionExtensions.GetAttribute<T>(classInstance, true);
}
public static T GetAttribute<T>(this object classInstance, bool includeInheritedAttributes) where T : class
{
if (classInstance == null)
return null;
Type t = classInstance.GetType();
object attr = t.GetCustomAttributes(includeInheritedAttributes).Where(a => a.GetType() == typeof(T)).FirstOrDefault();
return attr as T;
}
}
}
这会将我以前的答案变成:
class Program
{
static void Main(string[] args)
{
var classInstance = new SomePoco() { FirstName = "Bob" };
var tableNameAttribute = classInstance.GetAttribute<TableNameAttribute>();
Console.WriteLine(tableNameAttribute != null ? tableNameAttribute.TableName : "null");
Console.ReadKey(true);
}
}
答案 2 :(得分:2)
您可以使用Attribute.GetCustomAttribute
方法:
var tableNameAttribute = (TableNameAttribute)Attribute.GetCustomAttribute(
typeof(MyClass), typeof(TableNameAttribute), true);
然而,这对我的口味来说太冗长了,你可以通过以下小扩展方法让你的生活变得更加轻松:
public static class AttributeUtils
{
public static TAttribute GetAttribute<TAttribute>(this Type type, bool inherit = true) where TAttribute : Attribute
{
return (TAttribute)Attribute.GetCustomAttribute(type, typeof(TAttribute), inherit);
}
}
所以你可以简单地使用
var tableNameAttribute = typeof(MyClass).GetAttribute<TableNameAttribute>();