C#强类型属性成员来描述属性

时间:2013-06-01 11:52:33

标签: c# custom-attributes

我想知道是否可以声明描述属性的属性属性,因此需要强类型,理想情况下,intellisense可用于选择属性。通过将成员声明为类型类型,类类型可以很好地工作 但是如何将属性作为参数,以便“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; }
}

修改 为了避免使用属性名称字符串,我构建了一个简单的工具来保存编译时间检查,同时在地方存储和使用属性名称作为字符串。

这个想法是你通过intellisense帮助和类似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 个答案:

答案 0 :(得分: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; }
}