[英]C#: Can I or how to assign attributes to method parameters?
C# documentation says that you can assign custom attributes to parameters. C#文档说您可以为参数分配自定义属性。 The exact sentence is: "A target element can be an assembly, class, constructor, delegate, enum, event, field, interface, method, portable executable file module, parameter, property, return value, struct, or another attribute."
确切的句子是:“目标元素可以是程序集,类,构造函数,委托,枚举,事件,字段,接口,方法,可移植可执行文件模块,参数,属性,返回值,结构或其他属性。” Given that, what would be the correct syntax to do something like this:
鉴于此,做这样的事情的正确语法是什么:
private void SomeMethod
([CustomAttribute(Blah = "blah1")] string actualParam,
[CustomAttribute(Blah = "blah2")] DateTime anotherParam
)
{
// method's body
}
Or am I missing something entirely? 或者我完全错过了什么?
That's exactly like what you said. 这就像你说的那样。 For parameters, you'll do something like:
对于参数,您将执行以下操作:
void SomeMethod([MarshalAs(UnmanagedType.FunctionPtr)] Action del);
For return value, you'd do: 对于返回值,您可以:
[return: MyAttribute(Param1 = "Value1")]
int Method()
Similarly, there are [module: MyAttribute]
, [assembly: MyAttribute]
for modules and assemblies. 类似地,模块和程序集有
[module: MyAttribute]
, [assembly: MyAttribute]
。
Never mind, guys. 没关系,伙计们。 It's actually possible with the exact same syntax that I typed in question.
它实际上可能与我输入的语法完全相同。 The attribute class just needs to have the AttributeTargets.Parameter named parameter.
属性类只需要具有AttributeTargets.Parameter命名参数。 Sorry, it happens :)
对不起,它发生:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.