What is this parameter that has a colon in C# called?

狂风中的少年 提交于 2020-06-28 02:43:52

问题


I encountered something I've never seen before in C# (at least I don't recognize it anyways)...it's got me feeling pretty dumb at the moment.

I downloaded Dapper, which is awesome by the way, and was making my first query with a stored procedure.

connection.Query<MyObject>("[dbo].[sp_MyStoredProc]", new
{
    Name = keywords
}, commandType: CommandType.StoredProcedure);

The intellisense method signature says this should be an IDbTransaction. Is this some type of shorthand that converts:

commandType: CommandType.StoredProcedure

into an IDbTransaction?

Questions

  1. What is this called syntax called?
  2. What is happening here?

Thanks!


回答1:


That's called named arguments. See MSDN article Named and Optional Arguments (C# Programming Guide):

Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name.

Query method of Dapper has many parameters with default values (timeout, commandType etc). With this syntax you can specify only some of them without specifying others.




回答2:


It's a Named parameter, the query method has a commandType parameter which is being specified.

If you define a method like:

public static void SomeMethod(string arg1, int arg2)
{
}

you can specify the parameters by name e.g.

SomeMethod(arg1: "Some string", arg2: 3);

You can also specify them out of order:

SomeMethod(arg2: 3, arg1: "Some string");

One benefit of specifying parameters by name is when their meaning is not obvious by their position e.g. in Regex.Match:

var match = Regex.Match(@"^\d+$", "1234");    //wrong
var match = Regex.Match(pattern: @"^\d+$", input: "1234");


来源:https://stackoverflow.com/questions/21613388/what-is-this-parameter-that-has-a-colon-in-c-sharp-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!