Skip to main content
 首页 » 编程设计

C# 表达式树是完成任务的正确工具吗

2024年02月13日10findumars

我的示例项目是一个 MVC WebApi 项目。

标准 AuthorizeAttribute 采用 Roles = ""或 Users = ""参数。 我还没有看过实现,但我也不想:) 你能用表达式使这个更伪一点吗? 当您决定将属性的“角色”属性重命名为其他任何内容时,您会遇到编译时错误吗?

public interface IControllerContext 
{ 
    int MagicNumber { get; } 
    int ScaryNumber { get; } 
    string Version { get; } 
} 
 
public class AppAuthorizationAttribute : FilterAttribute 
{ 
    public IControllerContext SomeControllerContext 
    { 
       get; // implementation omitted 
    } 
 
    // ... 
} 
 
// This is my sample class which needs to be validated using the attribute. 
public class TestClass : BaseClass 
{ 
    [AppAuthorization((n) => n.MagicNumber == 13)] // or literally: which property and how to validate it" 
    protected void SomeMethodWhichRequiresPreProcessingValidation() 
    { 
        // do something. 
        // inside here I have access to an instance of ISomeContext 
        // and can do anything I want. 
    } 
} 

可选的奖励问题:是否可以通过某种方式从属性定义中访问当前 Controller (非静态)的字段?将 Controller 字段注入(inject)验证 lambda 表达式是一件很酷的事情。类似的东西: AppAuthorization((controller) => controller.SomePropertyHere.MagicNumer == 13)

请您参考如下方法:

属性声明只能使用simple types and constants .编译器不允许您使用表达式,因此您计划的方法将行不通。

您也不能引用字段或属性,只能引用常量。你能得到的最接近的东西是

public const MagicNumberPropertyName = "MagicNumber"; 
public enum Operator 
{ 
    Equals 
} 
 
[AppAuthorization(MagicNumberPropertyName, Operator.Equals, 13)] 
protected void Method() {}