且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C#中的参数属性访问对象值

更新时间:2023-02-09 15:20:35

不,属性实例对目标没有任何概念。

No, attribute instances don't have any notion of the target they're applied to.

请注意,通常您是从目标中获取属性,因此无论执行什么操作,获取信息都可能将信息提供给下一个目标。

Note that normally you fetch attributes from a target, so whatever's doing that fetching could potentially supply the information to whatever comes next. Potentially slightly annoying, but hopefully not infeasible.

所有这些的一个小例外是呼叫者信息属性-如果您使用类似的东西

One small exception to all of this is caller info attributes - if you use something like

[AttributeUsage(AttributeTargets.Parameter)]
public class ValidateMetaFieldsAttribute : Attribute
{
    public ValidateMetaFieldsAttribute([CallerMemberName] string member = null)
    {
        ...
    }
}

...,则在这种情况下,即使该属性已应用于方法名称( SaveComponent ),编译器仍将填写该名称。参数。同样,您可以获取文件路径和行号。

... then the compiler will fill in the method name (SaveComponent) in this case, even though the attribute is applied to the parameter. Likewise you can get at the file path and line number.

鉴于此目的,请注意此注释,但我认为您遇到了更大的问题:

Given this comment about the purpose, however, I think you've got a bigger problem:


在方法体运行之前验证componentToSave并抛出异常。

To validate componentToSave and throw an exception before method body even runs.

仅当获取属性时,才执行属性构造函数中的代码。例如,在每个方法调用上执行。

The code in the attribute constructor will only be executed if the attribute is fetched. It's not executed on each method call, for example. This may well make whatever you're expecting infeasible.

您可能想研究AOP,例如与 PostSharp

You may want to look into AOP instead, e.g. with PostSharp.