2013-06-01 84 views
1

我想知道是否有可能聲明一個屬性屬性,描述一個屬性,所以強打字是必需的,理想情況下,智能感知可以用來選擇屬性。類類型很好地通過聲明該成員類型類型 但如何獲取屬性作爲參數,以便「PropName」不被引用和強類型?C#強類型屬性成員來描述屬性

到目前爲止:本Attibute類和樣品的使用看起來像

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 
public class MyMeta : Attribute{ 
    public Type SomeType { get; set; } // works they Way I like. 
    // but now some declaration for a property that triggers strong typing 
    // and ideally intellisense support, 
    public PropertyInfo Property { get; set; } //almost, no intellisence type.Prop "PropName" is required 
    public ? SomeProp {get;set;} // <<<<<<< any ideas of nice type to define a property 
} 

public class Example{ 
    [MyMeta(SomeType = typeof(SomeOtherClass))] //is strongly typed and get intellisense support... 
    public string SomeClassProp { get; set; } 
    [MyMeta(SomeProp = Class.Member)] // <<< would be nice....any ideas ? 
    public string ClassProp2 { get; set; } 
    // instead of 
    [MyMeta(SomeProp = typeof(T).GetProperty("name")] // ... not so nice 
    public string ClassProp3 { get; set; } 
} 

編輯: 爲了避免使用屬性名字符串我建了一個簡單的工具,以保持編譯時檢查,同時在存儲和使用屬性名稱作爲字符串放置。

這個想法是,你可以通過它的類型和名稱快速引用屬性,並使用intellisense幫助和代碼完成來自like resharper。然後將一個STRING傳遞給一個工具。

I use a resharper template with this code shell 

string propname = Utilites.PropNameAsExpr((SomeType p) => p.SomeProperty) 

是指

public class Utilities{ 
    public static string PropNameAsExpr<TPoco, TProp>(Expression<Func<TPoco, TProp>> prop) 
    { 
     //var tname = typeof(TPoco); 
     var body = prop.Body as System.Linq.Expressions.MemberExpression; 
     return body == null ? null : body.Member.Name; 
    } 
} 

回答

1

不,這是不可能的。您可以使用typeof作爲類型名稱,但必須使用字符串作爲成員名稱。這是儘可能你可以得到:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 
public class MyMeta : Attribute{ 
    public Type SomeType { get; set; } 
    public string PropertyName {get;set;} 
    public PropertyInfo Property { get { return /* get the PropertyInfo with reflection */; } } 
} 

public class Example{ 
    [MyMeta(SomeType = typeof(SomeOtherClass))] //is strongly typed and get intellisense support... 
    public string SomeClassProp { get; set; } 
    [MyMeta(SomeType = typeof(SomeOtherClass), PropertyName = "SomeOtherProperty")] 
    public string ClassProp2 { get; set; } 
} 
+1

好的謝謝,不是我希望看到的答案。沒有強大的會員作爲參數打字:-( –

+0

我會標記爲答案,直到有人證明你錯了;-)在另一個7分鐘 –