传递带有变量值的自定义属性作为参数

传递带有变量值的自定义属性作为参数

本文介绍了传递带有变量值的自定义属性作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我创建了一个自定义属性类,该类将检查系统安全性,并在出现安全性错误时引发身份验证异常.

I created a custom attribute class that will check the system security and throws an authentication exception if there is a security error.

public class EntityChecker: System.Attribute
{
    public EntityChecker(int entityId)
    {
        // doing some logic to check if the entityId is allowed to be inserted
    }
}

我想将此自定义属性用作对实体加法函数的声明,并且希望将变量从该函数传递给属性构造函数.可以这样做吗?

I want to use this custom attribute as a declaration to an entity addition function and I want to pass a variable from the function to the attribute constructor. can something like this be done?

[EntityChecker(entityId)]
public int AddNewEntity(entityId)
{
 // logic of entity addition
}

推荐答案

不.必须在编译时 解析属性中的构造函数参数.它们旨在作为类型或方法本身上的元数据,而不是用于每次调用或每个实例的内容.

No. Constructor parameters in attributes must be resolved at compile time. They are intended as metadata on the type or method itself, not something that would be used per call or per instance.

鉴于您的描述,属性可能不是处理此问题的适当方法.由于您想运行每次调用都会发生的额外代码,因此您将需要另一种技术.例如,您可以传递一个委托,即:

Given your description, an attribute is likely not an appropriate way to handle this. Since you want to run extra code that happens per call, you will need a different technique. For example, you could pass a delegate, ie:

public int CheckedAddEntity(int entityId, Func<int, int> funcToAdd)
{
    // Perform your checking on entityId here
    return funcToAdd();
}

这将使您可以通过类似的方式拨打电话:

This would let you then call via something like:

int result = CheckedAddEntity(entityId, AddNewEntity);

这篇关于传递带有变量值的自定义属性作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:35