c# - 如何定义命名参数 C#

标签 c# .net custom-attributes named-parameters

这似乎是一个简单的问题,但出于某种原因我无法在任何地方找到答案。基本上,我希望能够实现采用NamedParameters 的构造函数。

我所说的命名参数并不是指具有默认值(可选参数)的参数,例如:

public SomeMethod(){
    string newBar = Foo(bar2 : "customBar2");
}

public string Foo(string bar1 = "bar1", bar2 = "bar2" ){
     //...
}

System.Web.Mvc 程序集中的 AuthorizeAttribute 是我试图实现的一个很好的例子。您可以通过以下方式使用:

[Authorize(Roles = "Administrators", Users = "ThatCoolGuy")]
public ActionResult Admin(){

}

intellisense 中的构造函数签名如下例所示,我相信(请确认)那些 NamedParameters 正在映射到类属性。

AuthorizeAttribute.AuthorizeAttribute(NamedParameters...) Initiliaze new instance of the System.Web.Mvc.AuthorizeAttribute class

Named parameters:

  • Order int
  • Users string
  • Roles string

最佳答案

请注意:

调用方法时定义参数名的语法与可选参数无关:

您可以使用 Foo(bar1 : "customBar1"); 即使 Foo 声明如下:void Foo(string bar1)


回答问题:
我的猜测是,这是类似于 object initializers 的语法糖。在 Visual Studio 2010 中引入,因此您不能将其用于您自己的类。

关于c# - 如何定义命名参数 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12056639/

相关文章:

c# - 如何修复 'Type of conditional expression cannot be determined'

c# - 创建 C# 属性以抑制方法执行

Objective-C:自定义 BOOL 访问器(getter 和 setter)方法

c# - 为代码设置 ASP.NET 结构

c# - 在多个过滤器中使用相同的 lambda 参数

c# - 字节数组转base64字符串

asp.net-mvc-3 - 从属性抛出时如何捕获 Controller 中的错误?

c# - 如何以线程安全的方式调用 .NET ConcurrentDictionary 上的 GetOrAdd 方法?

.net - 在某些情况下我们仍然会使用非泛型集合吗?

c# - ASP.NET - 从数据库中检索图像列表并将它们显示在 View 中?