[英]C# Strongly Typed Attribute member to describe property
我想知道是否可以声明一个描述属性的Attribute属性,因此需要强类型输入,并且理想情况下可以使用intellisense来选择该属性。 通过将成员声明为Type Type, Class Types可以很好地工作。但是如何获取属性作为参数,以便不引用“ PropName”并对其进行强类型化?
到目前为止: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; }
}
编辑:为避免使用属性名称字符串,我构建了一个简单的工具来在存储和使用属性名称作为字符串的同时保持编译时间检查。
这样的想法是,您可以借助智能感知功能通过代码的类型和名称快速引用属性,并像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;
}
}
不,不可能。 您可以将typeof
用作Type名称,但必须使用字符串作为成员名称。 这是您可以得到的:
[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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.