【问题标题】:Attribute contents extracion属性内容提取
【发布时间】:2018-04-01 12:10:18
【问题描述】:

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

属性:

[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))

有没有办法重写属性内容提取方法来简化/缩短它的调用。由于它的长度,它对我来说太不方便了。

CallerMemberNameAttribute 之类的东西会很棒,但我什么也没找到。

【问题讨论】:

  • 我觉得还可以
  • 我正在寻找将其插入字符串的方法,每个字符串 2..5 次调用,但当前调用语法对它来说太长了

标签: c# reflection properties attributes


【解决方案1】:

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

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

输出是一样的:

某人的名字

某人的名字

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-02
    • 2017-09-19
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多