Pie*_* SS 17 .net c# custom-attributes named-parameters
这似乎是一个简单的问题,但由于某种原因,我无法在任何地方找到答案.基本上,我希望能够实现一个带NamedParameters的构造函数.
通过命名参数,我不是指具有默认值(可选参数)的参数,例如:
public SomeMethod(){
string newBar = Foo(bar2 : "customBar2");
}
public string Foo(string bar1 = "bar1", bar2 = "bar2" ){
//...
}
Run Code Online (Sandbox Code Playgroud)
什么我想实现一个很好的例子是AuthorizeAttribute从System.Web.Mvc装配.您可以使用以下方式:
[Authorize(Roles = "Administrators", Users = "ThatCoolGuy")]
public ActionResult Admin(){
}
Run Code Online (Sandbox Code Playgroud)
intellisense中构造函数的签名类似于以下示例,我相信(请确认)那些NamedParameters正在映射到类属性.
AuthorizeAttribute.AuthorizeAttribute(NamedParameters ...)Initiliaze System.Web.Mvc.AuthorizeAttribute类的新实例
命名参数:
- 订单int
- 用户字符串
- 角色字符串
mat*_*ieu 14
您所讨论的行为是特定于属性的,不能在"普通"类构造函数中重用.
你不需要"实施"任何东西.
参数可以按照您在构造函数中作为参数的现有描述的方式使用.
你也需要使用C#3.5或以上,他们推出的时候.
您的示例将在C#4.0/Visual Studio 2010上编译和运行,无需修改.
请参阅MSDN上的命名和可选参数(C#编程指南).
关于对象的属性,没有相应的构造函数参数,确切的语法是特定于属性的,并且无法复制,但是,使用对象初始值设定项,您可以接近.