LAMBDA EX pression的属性构造属性、LAMBDA、EX、pression

2023-09-03 08:59:05 作者:怣

我已经创建了一个属性名为 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; }
}

我想用拉姆达EX pressions,这样我可以通过一个强类型到我的属性的构造函数,而不是一个神奇字符串。这样我可以利用编译器的类型检查。例如:

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?

推荐答案

您不能

您不能创建通用属性类型(它根本是不允许的);同样,没有语法的使用的通用属性( [美孚&LT; SOMETYPE&GT;] )的定义 您不能使用属性初始化lambda表达式 - 可传递给属性的值是非常有限的,根本不包含EX pressions(这是非常复杂的,而且运行时对象,而不是编译时面值) 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)