【问题标题】:C# Strongly Typed Attribute member to describe propertyC#强类型属性成员来描述属性
【发布时间】:2013-06-01 11:52:33
【问题描述】:

我想知道是否可以声明一个描述属性的 Attribute 属性,因此需要如此强的类型,理想情况下,智能感知可以用来选择该属性。 Class Types 通过将成员声明为 Type Type 可以很好地工作 但是如何获取属性作为参数,使得“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;
    }
 }

【问题讨论】:

    标签: c# custom-attributes


    【解决方案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; }
    }
    

    【讨论】:

    • 好的,谢谢,这不是我希望看到的答案。成员没有强类型作为参数:-(
    • 我会标记为答案,直到有人证明你错了 ;-) 再过 7 分钟
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多