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

ova*_*g25 4 c# petapoco

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

例如,如果我有以下类:

...
[TableName("my_table_name")]
public class MyClass
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我可以这样做:

MyClass.Attribute.TableName => my_table_name
Run Code Online (Sandbox Code Playgroud)

谢谢!

Rya*_*ann 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);
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)


Iva*_*oev 5

您可以使用Attribute.GetCustomAttribute以下方法:

var tableNameAttribute = (TableNameAttribute)Attribute.GetCustomAttribute(
    typeof(MyClass), typeof(TableNameAttribute), true);
Run Code Online (Sandbox Code Playgroud)

然而,这对我来说太冗长了,你可以通过以下小扩展方法让你的生活变得更轻松:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以简单地使用

var tableNameAttribute = typeof(MyClass).GetAttribute<TableNameAttribute>();
Run Code Online (Sandbox Code Playgroud)