我创建了一个自定义属性类,它将检查系统安全性,并在存在安全错误时引发身份验证异常。
public class EntityChecker: System.Attribute
{
public EntityChecker(int entityId)
{
// doing some logic to check if the entityId is allowed to be inserted
}
}
我想使用此自定义属性作为实体添加函数的声明,并且想将变量从函数传递到属性构造函数。这样的事情可以做吗?
[EntityChecker(entityId)]
public int AddNewEntity(entityId)
{
// logic of entity addition
}
这样的事还能做吗?!
否。属性中的构造函数参数必须解析在编译时。它们旨在作为元数据类型或方法本身,而不是每次调用或每个实例都会使用的东西。
根据您的描述,属性可能不是处理此问题的适当方法。由于您希望运行每次调用时发生的额外代码,因此您将需要不同的技术。例如,您可以传递一个委托,即:
public int CheckedAddEntity(int entityId, Func<int, int> funcToAdd)
{
// Perform your checking on entityId here
return funcToAdd();
}
这可以让你通过类似的方式调用:
int result = CheckedAddEntity(entityId, AddNewEntity);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)