如何定义命名参数C# [英] How to define named Parameters C#

查看:117
本文介绍了如何定义命名参数C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

通过命名参数,我不是说使用默认值的参数(可选参数),例如:

 公开的someMethod(){
    字符串newBar =美孚(BAR2:customBar2);
}

公共字符串美孚(字符串BAR1 =BAR1,BAR2 =BAR2){
     // ...
}
 

什么我想达到一个很好的例子是在 AuthorizeAttribute System.Web.Mvc 组装。您可以使用以下方式:

  [授权(角色=管理员,用户=ThatCoolGuy)
公众的ActionResult管理员(){

}
 

在智能感知的构造函数的签名看起来像下面的例子,我相信(请确认),这些NamedParameters映射到的类属性。

  

AuthorizeAttribute.AuthorizeAttribute( NamedParameters ... )   Initiliaze的System.Web.Mvc.AuthorizeAttribute类的新实例

     

命名参数:

     
      
  • 订单INT
  •   
  • 用户字符串
  •   
  • 角色串
  •   
解决方案

你所谈论的行为是具体的属性,不能在正常类的构造函数重复使用。

This seems like a simple question, but for some reason I can't find the answer anywhere. Basically, I'd like to be able to implement a constructor that takes NamedParameters.

By named parameters, I do not mean parameters with default values (optional parameters) such as:

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

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

A good example of what I'm trying to achieve is the AuthorizeAttribute from the System.Web.Mvc assembly. Which you can use the following way:

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

}

The constructor's signature in intellisense looks like the following example and I believe (please confirm) that those NamedParameters are mapping to class properties.

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

Named parameters:

  • Order int
  • Users string
  • Roles string

解决方案

The behaviour you are talking about is specific for attributes and cannot be reused in "normal" classes constructors.

这篇关于如何定义命名参数C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆