c#强类型属性成员,用于描述属性



我想知道是否有可能声明一个Attribute属性来描述一个需要强类型的属性,并且理想情况下可以使用智能感知来选择属性。通过将成员声明为TypeType,类类型可以很好地工作。但是如何获得属性作为参数,使"PropName"不引号和强类型?

到目前为止:属性类和示例用法看起来像

 [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作为类型名,但必须使用字符串作为成员名。这是你所能得到的:

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

最新更新