c# ienumerable 赋值_[C#.NET 拾遗补漏]03:你可能不知道的几种对象初始化方式

1a9d21c9a76972d66a99fd7d6c1ad36d.png

随着 C# 的升级,C# 在语法上对对象的初始化做了不少简化,来看看有没有你不知道的。

数组的初始化

在上一篇罗列数组的小知识的时候,其中也提到了数组的初始化,这时直接引用过来。

int[] arr = new int[3] {1, 2, 3}; // 正儿八经的初始化
int[] arr = new [] {1, 2, 3};     // 简化掉了 int 和数组容量声明
int[] arr = {1, 2, 3};            // 终极简化

字典的两种初始化方式

第二种是 C# 6 的语法,可能很多人不知道。

// 方式一:
var dict = new Dictionary<string, int>
{
    { "key1", 1 },
    { "key2", 20 }
};

// 方式二:
var dict = new Dictionary<string, int>
{
    ["key1"] = 1,
    ["key2"] = 20
};

含自定义索引器的对象初始化

这种初始化原理上其实是和上面字典的第二种初始化是一样的。

public class IndexableClass
{
    public int this[int index]
    {
        set
        {
            Console.WriteLine("{0} was assigned to index {1}", value, index);
        }
    }
}

var foo = new IndexableClass
{
    [0] = 10,
    [1] = 20
}

元组(Tuple)的三种初始化方式

前面两种方式很常见,后面一种是 C# 7 的语法,可能有些人不知道。

// 方式一:
var tuple = new Tuple<string, int, MyClass>("foo", 123, new MyClass());

// 方式二:
var tuple = Tuple.Create("foo", 123, new MyClass());

// 方式三:
var tuple = ("foo", 123, new MyClass());

另外补充个小知识,在 C# 7 中,元组的元素可以被解构命名:

(int number, bool flage) tuple = (123, true);
Console.WriteLine(tuple.number); // 123
Console.WriteLine(tuple.flag);   // True

自定义集合类的初始化

只要自定义集合类包含Add方法,便可以使用下面这种初始化方式为集合初始化元素。

class Program
{
    static void Main()
    {
        var collection = new MyCollection {
            "foo",         // 对应方法:Add(string item)
            { "bar", 3 },  // 对应方法:Add(string item, int count)
            "baz",         // 对应方法:Add(string item)
            123.45d,       // 对应扩展方法:Add(this MyCollection @this, double value)
        };
    }
}

class MyCollection : IEnumerable
{
    privatereadonly IList _list = new ArrayList();

    public void Add(string item)
    {
        _list.Add(item);
    }

    public void Add(string item, int count)
    {
        for (int i = 0; i < count; i++)
        {
            _list.Add(item);
        }
    }

    public IEnumerator GetEnumerator()
    {
        return _list.GetEnumerator();
    }
}

static class MyCollectionExtensions
{
    public static void Add(this MyCollection @this, double value) =>
        @this.Add(value.ToString());
}

对象的集合属性初始化

我们知道对集合的初始化必须使用new创建该集合,不能省略,比如:

// OK
IList<string> synonyms = new List<string> { "c#", "c-sharp" };

// 编译报错,不能省略 new List<string>
IList<string> synonyms = { "c#", "c-sharp" };

但如果该集合作为另外一个类的属性,则可以省略new,比如:

public class Tag
{
    public IList<string> Synonyms { get; set; } = new List<string>();
}

var tag = new Tag
{
    Synonyms = { "c#", "c-sharp" } // OK
};

能想到和找到的就这么点了,希望以上会对你的编程有所帮助。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值