问题描述
我创建了一个名为 RelatedPropertyAttribute
的 Attribute
类:
I have created an Attribute
class called RelatedPropertyAttribute
:
[AttributeUsage(AttributeTargets.Property)]
public class RelatedPropertyAttribute: Attribute
{
public string RelatedProperty { get; private set; }
public RelatedPropertyAttribute(string relatedProperty)
{
RelatedProperty = relatedProperty;
}
}
我用它来表示类中的相关属性.我将如何使用它的示例:
I use this to indicate related properties in a class. Example of how I would use it:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty("EmployeeID")]
public int EmployeeNumber { get; set; }
}
我想使用 lambda 表达式,以便将强类型传递给属性的构造函数,而不是魔术字符串".这样我可以利用编译器类型检查.例如:
I would like to use lambda expressions so that I can pass a strong type into my attribute's constructor, and not a "magic string". This way I can exploit compiler type checking. For example:
public class MyClass
{
public int EmployeeID { get; set; }
[RelatedProperty(x => x.EmployeeID)]
public int EmployeeNumber { get; set; }
}
我以为我可以用以下方法做到这一点,但编译器不允许这样做:
I thought I could do it with the following, but it isn't allowed by the compiler:
public RelatedPropertyAttribute<TProperty>(Expression<Func<MyClass, TProperty>> propertyExpression)
{ ... }
错误:
非泛型类型RelatedPropertyAttribute"不能与类型参数
The non-generic type 'RelatedPropertyAttribute' cannot be used with type arguments
我怎样才能做到这一点?
How can I achieve this?
推荐答案
你不能
- 您不能创建通用属性类型(根本不允许这样做);同样,没有定义 使用 通用属性 (
[Foo<SomeType>]
) 的语法 - 您不能在属性初始值设定项中使用 lambda - 可传递给属性的值非常有限,并且根本不包括表达式(非常复杂,并且是运行时对象,而不是编译时文字)
- you cannot create generic attribute types (it simply isn't allowed); equally, no syntax for using generic attributes (
[Foo<SomeType>]
) is defined - you cannot use lambdas in attribute initializers - the values available to pass to attributes is very limited, and simply does not include expressions (which are very complex, and are runtime objects, not compile-time literals)
这篇关于属性构造函数中的 Lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!