C # Strongly typed attribute member to describe property

I was wondering if it is possible to declare an Attribute property that describes the property, so strong typing is required and ideally what intellisense can use to select the property. Class types work fine by declaring a member as Type Type. But how to get a property as a parameter so that "PropName" is not quoted and strongly typed?

So far: the Attibute class and sample usage look like

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

EDIT: To avoid using property name strings, I built a simple tool that allows you to save compile-time checks during storage and use property names in places as strings.

The idea is that you quickly reference a property through its type and name using intellisense help and code completion from a similar resharper. However, pass STRING to the tool.

 I use a resharper template with this code shell string propname = Utilites.PropNameAsExpr( (SomeType p) => p.SomeProperty ) 

which refers to

 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
c # custom-attributes
source share
1 answer

No, It is Immpossible. You can use typeof for the type name, but you must use a string for the member name. This is how much you can get:

 [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
source share

All Articles