属性构造函数中的 Lambda 表达式

Lambda expression in attribute constructor(属性构造函数中的 Lambda 表达式)
本文介绍了属性构造函数中的 Lambda 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个名为 RelatedPropertyAttributeAttribute 类:

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 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to pass lambda #39;include#39; with multiple levels in Entity Framework Core?(如何在 Entity Framework Core 中传递具有多个级别的 lambda include?)
Join/Where with LINQ and Lambda(使用 LINQ 和 Lambda 加入/在哪里)
Getting all types that implement an interface(获取所有实现接口的类型)
Combining two expressions (Expressionlt;Funclt;T, boolgt;gt;)(组合两个表达式 (ExpressionFuncT, boolgt;))
Is there a reason for C##39;s reuse of the variable in a foreach?(C# 在 foreach 中重用变量是否有原因?)
Lambda/Linq with Contains criteria for multiple keywords(Lambda/LINQ WITH包含多个关键字的条件)