您可以为类使用类似数组的构造函数吗

aXu*_*_AP 4 c# constructor

是否可以让类构造函数表现得像数组初始值设定项,例如Foo foo = { 1, 2, 3 };

通过隐式转换,我非常接近:Foo foo = new int[] { 1, 2, 3 };

但我很想添加更多的语法糖,因为这部分将在我的整个代码中使用。使其更像 JSON。

Mat*_*son 5

IEnumerable<T>如果您的类实现了集合中项目的类型,Add(T)您可以相当接近。T

例如,考虑到:

public sealed class Foo: IEnumerable<int>
{
    public void Add(int item)
    {
        _items.Add(item);
    }

    public IEnumerator<int> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    readonly List<int> _items = new List<int>();
}
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

Foo foo = new Foo {1, 2, 3};
Run Code Online (Sandbox Code Playgroud)

不幸的是,以下语法仅为数组保留:

Foo foo = {1, 2, 3}; // Won't compile. You need the "new Foo".
Run Code Online (Sandbox Code Playgroud)