这似乎是一个简单的问题,但出于某种原因我无法在任何地方找到答案。基本上,我希望能够实现采用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/