2017-10-20 266 views
1

我試圖簡化從屬性提取數據的代碼。屬性內容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會很棒,但我什麼也沒找到。

+0

這看起來不錯,我 – Backs

+0

我查看fow的方式將其插入到字符串中,每個字符串2..5個調用,但當前調用語法對於它來說太長 –

回答

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