简体   繁体   English

C#:我可以或如何为方法参数指定属性吗?

[英]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.

相关问题 如何在C#中包装带有可选参数的方法? - How can I wrap a method with optional parameters in C#? C# - 在一个方法中,我怎样才能有 2 个参数是一个? - C# - In a method, how can I have 2 parameters that are one? 如何使用c#属性? - How can I use c# attributes? C#-如何确保静态方法直接影响其参数,而不仅仅是实例? - C# - How can I insure a static method effects its parameters directly and not just instances? C#MVC - 如何在Controller中传递一些方法参数作为参数? - C# MVC - How can I pass some method arguments as parameters inside a Controller? 如何使用C#通过POST方法将参数从网站发布到HttpHandler - How can I post parameters from web site to HttpHandler with POST method using C# 如何在 C# 中以纯文本形式获取方法的参数? - How can I get a method's parameters in plain text in C#? 如何通过 Kubernetes c# API 方法“WebSocketNamespacedPodExecAsync”执行带参数的命令? - How can I execute a command with parameters though Kubernetes c# API method “WebSocketNamespacedPodExecAsync”? 如何使用动态参数调用方法(可以通过或不通过)C# - How to call a method with dynamic parameters (can pass or without) C# 如何在C#中的for循环内分配不同的迭代? - How can I assign different iteration within for loop in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM