简体   繁体   中英

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 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM