我有办法访问 C# class 属性吗?

Is there a way for me to access a C# class attribute?

我有办法访问 C# class 属性吗?

例如,如果我有以下 class:

...
[TableName("my_table_name")]
public class MyClass
{
    ...
}

我可以做类似的事情吗:

MyClass.Attribute.TableName => my_table_name

谢谢!

可以使用反射来获取。这是一个完整的示例:

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);
        }
    }    
}

这里有一个扩展,通过扩展 object 来为您提供一个属性助手,从而使它变得更容易。

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);
    }
}   

您可以使用 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>();