c#语法快捷方式,用于在连续多次引用对象名称时跳过该对象名称

Coo*_*Bro 5 c# syntax shortcut

c#中是否有任何可以简化此操作的快捷方式:

List<string> exampleList = new List<string>();
exampleList.Add("Is");
exampleList.Add("it");
exampleList.Add("possible");
Run Code Online (Sandbox Code Playgroud)

和这样的事情:

 var exampleList = new List<string>();
 exampleList {
.Add("is");
.Add("it");
.Add("possible");
}
Run Code Online (Sandbox Code Playgroud)

我知道可以在声明期间分配属性,如下所示:

var myObject = new MyObject{
Id = "Useful",
Name = "Shortcut"
};
Run Code Online (Sandbox Code Playgroud)

知道是否有其他有用的快捷方式会很有趣,但我找不到任何快捷方式.

Mar*_*ell 6

var exampleList = new List<string>() {
    "Yes", "kinda", "with", "collection", "initializers" };
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以对多参数Add方法执行此操作,例如词典:

var lookup = new Dictionary<string, int> {
    {"abc", 124}, {"def",456}
};
Run Code Online (Sandbox Code Playgroud)


Mat*_*son 5

你可以写一个扩展方法:

public static class ListExt
{
    public static List<T> Append<T>(this List<T> self, params T[] items)
    {
        if (items != null && self != null)
            self.AddRange(items);

        return self;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

List<string> list = new List<string>();

list.Append("Or", "you", "can", "use", "an", "extension", "method");

list.Append("Or").Append("like").Append("this");
Run Code Online (Sandbox Code Playgroud)