【发布时间】:2013-05-24 10:36:47
【问题描述】:
我创建了一个名为RelatedPropertyAttribute 的Attribute 类:
[AttributeUsage(AttributeTargets.Property)]
public class RelatedPropertyAttribute: Attribute
{
public string RelatedProperty { get; private set; }
public RelatedPropertyAttribute(string relatedProperty)
{
RelatedProperty = relatedProperty;
}
}
我用它来表示类中的相关属性。我将如何使用它的示例:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty("EmployeeID")]
public int EmployeeNumber { get; set; }
}
我想使用 lambda 表达式,以便将强类型传递给属性的构造函数,而不是“魔术字符串”。这样我可以利用编译器类型检查。例如:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty(x => x.EmployeeID)]
public int EmployeeNumber { get; set; }
}
我以为我可以用以下方法做到这一点,但编译器不允许这样做:
public RelatedPropertyAttribute<TProperty>(Expression<Func<MyClass, TProperty>> propertyExpression)
{ ... }
错误:
非泛型类型“RelatedPropertyAttribute”不能与 类型参数
我怎样才能做到这一点?
【问题讨论】:
-
尝试使类成为通用类..而不是单独的构造函数。
-
我认为属性参数仅限于
compile-time constants, typeof expression or array creation expression of an attribute parameter type。您甚至不能将小数作为参数传递。看看stackoverflow.com/questions/11004909/… -
泛型类型不能从“属性”派生,因为它是一个属性类
-
可能像[PostSharp][postsharp.net/]这样的工具可以帮你解决。它可以在.NET编译器执行之前集成到构建过程中生成代码。
-
没有时间给出完整的答案,但实现最终目标的一种方法是:让班级拥有
Tuple<,>s 和Expression<Func<class,object>>s 的静态列表;此列表中的每个条目都是相关属性的 getter 元组。这在编译时是强大的,并且在执行时也是可查询的。
标签: c# .net reflection attributes custom-attributes