我创建了一个名为 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>]
) 的语法[Foo<SomeType>]
) is defined这篇关于属性构造函数中的 Lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!