属性内容extracion
问题描述:
我试图简化从属性提取数据的代码。属性内容extracion
属性:
[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;
}
Sample类:
class TestClass
{
[Column("SomeName")]
public object NamedProperty { get; set; }
}
呼叫样品:
var name = GetName<TestClass>(nameof(TestClass.NamedProperty))
重写属性内容提取方法来简化/缩短它的调用有什么方法吗?由于它的长度,对我来说太不方便了。
就像CallerMemberNameAttribute会很棒,但我什么也没找到。
答
您的语法已经很短了。唯一的冗余信息是班级名称,其他一切都是需要,它不会变得更短。如下所示,您可以在您的调用中使用较短的语法,在此删除类名的冗余。但是,这需要付出代价或更复杂的实施。它是由你来决定,如果这是值得的:
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
这看起来不错,我 – Backs
我查看fow的方式将其插入到字符串中,每个字符串2..5个调用,但当前调用语法对于它来说太长 –