属性内容提取

时间:2017-10-20 10:21:48

标签: c# reflection properties attributes

我试图简化从属性属性中提取数据的代码。

属性:

[AttributeUsage(AttributeTargets.Property)]
class NameAttribute : Attribute
{
    public string Name { get; }

    public ColumnAttribute(string name)
    {
        Name = name;
    }
}

属性内容提取代码(删除了空检查):

public static string GetName<T>(string propName)
{
    var propertyInfo = typeof(T).GetProperty(propName);
    var nameAttribute = (NameAttribute)propertyInfo.GetCustomAttributes(typeof(NameAttribute)).FirstOrDefault();
    return nameAttribute.Name;
}

示例类:

class TestClass
{
    [Column("SomeName")]
    public object NamedProperty { get; set; }
}

致电样本:

var name = GetName<TestClass>(nameof(TestClass.NamedProperty))

是否可以通过重写属性内容提取方法来简化/缩短其调用。由于它的长度,对我来说太不方便了。

question之类的东西会很棒,但我一无所获。

1 个答案:

答案 0 :(得分:0)

您的语法已经很短了。唯一的冗余信息是类名,其他一切都是需要,它不会变得更短。您可以在调用时使用较短的语法,如下所示,删除类名的冗余。然而,这需要付出代价或更复杂的实施。由你来决定是否值得:

namespace ConsoleApp2
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    static class Program
    {
        // your old method:
        public static string GetName<T>(string propName)
        {
            var propertyInfo = typeof(T).GetProperty(propName);

            var nameAttribute = propertyInfo.GetCustomAttribute(typeof(NameAttribute)) as NameAttribute;

            return nameAttribute.Name;
        }

        // new syntax method. Still calls your old method under the hood.
        public static string GetName<TClass, TProperty>(Expression<Func<TClass, TProperty>> action)
        {
            MemberExpression expression = action.Body as MemberExpression;
            return GetName<TClass>(expression.Member.Name);
        }

        static void Main()
        {
            // you had to type "TestClass" twice
            var name = GetName<TestClass>(nameof(TestClass.NamedProperty));

            // slightly less intuitive, but no redundant information anymore
            var name2 = GetName((TestClass x) => x.NamedProperty);

            Console.WriteLine(name);
            Console.WriteLine(name2);
            Console.ReadLine();
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    class NameAttribute : Attribute
    {
        public string Name { get; }

        public NameAttribute(string name)
        {
            this.Name = name;
        }
    }

    class TestClass
    {
        [Name("SomeName")]
        public object NamedProperty { get; set; }
    }
}

输出相同:

  

SomeName

     

SomeName