描述属性的C#强类型属性成员
我想知道是否可以声明一个属性属性,该属性描述了一个需要强类型的属性,理想情况下可以使用intellisense来选择该属性。类类型通过将成员声明为TypeType 但如何获取属性作为参数,以便“PropName”不被引用且是强类型的 到目前为止:Attibute类和示例用法如下描述属性的C#强类型属性成员,c#,custom-attributes,C#,Custom Attributes,我想知道是否可以声明一个属性属性,该属性描述了一个需要强类型的属性,理想情况下可以使用intellisense来选择该属性。类类型通过将成员声明为TypeType 但如何获取属性作为参数,以便“PropName”不被引用且是强类型的 到目前为止:Attibute类和示例用法如下 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class MyMeta : Attribute{ publi
[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; }
}
指的是
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;
}
}
公共类实用程序{
公共静态字符串PropNameAsExpr(表达式属性)
{
//var tname=类型(TPoco);
var body=prop.body作为System.Linq.Expressions.MemberExpression;
返回body==null?null:body.Member.Name;
}
}
不,不可能。您可以使用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; }
}
好的,谢谢,这不是我希望看到的答案。没有强输入成员作为参数:-(我将标记为答案,直到有人证明你错了;-)再过7分钟
[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; }
}