开发者

C#: Can I or how to assign attributes to method parameters?

C# documentation says that you can assign custom attributes to parameters. 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 开发者_StackOverflow社区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.


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. Sorry, it happens :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜