如何创建一个类似数组的 C# 构造函数,允许“new MyClass() { obj1, obj2, obj3 };”

发布于 2024-10-27 16:34:57 字数 191 浏览 0 评论 0原文

我正在尝试创建一个类,它接受类似于字典、列表或数组的构造函数,您可以在其中使用对象的文字集合创建对象,尽管我一直无法找到如何创建这样的构造函数,如果可能的话。

MyClass obj = new MyClass()
{
    { value1, value2 },
    { value3, value4 }
}

I'm trying to create a class that accepts a constructor similar to that of a dictionary, list, or array where you can create the object with a literal collection of objects, though I have been unable to find how to create such a constructor, if it's even possible.

MyClass obj = new MyClass()
{
    { value1, value2 },
    { value3, value4 }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

失退 2024-11-03 16:34:57

要使集合初始值设定项起作用,您需要做两件事:

  1. 实现与集合初始值设定项匹配的 IEnumerable(非泛型版本)Add() 方法

一个类似于 IDictionary 的示例:

class Program
{
    static void Main(string[] args)
    {
        MyClass obj = new MyClass()
        {
            {value1, value2},
            {value3, value4}
        };
    }
}

public class MyClass : IEnumerable
{
    public void Add(object x, object y)
    {

    }

    public IEnumerator GetEnumerator()
    {
    }
}

下面 集合初始值设定项代码字面上翻译为:

MyClass temp = new MyClass();
temp.Add(value1, value2);
temp.Add(value3, value4);
MyClass obj = temp;

由于临时变量,如果任何 Add() 调用生成异常,则命名变量(在本例中为 obj ) 从未被实际分配。有趣的是,这也意味着如果MyClass要实现IDisposable,那么当以下任一情况时,Dispose()将不会在构造的对象上被调用: Add() 方法会生成错误(我对此进行了测试以确保)。

为什么需要 IEnumerable?因为该接口区分了用于集合的使用 Add 的类和用于计算的使用 Add 的类。

http://blogs.msdn .com/b/madst/archive/2006/10/10/what-is-a-collection_3f00_.aspx

[当您使用Add分析类时]您会意识到“Add”这个名称本质上有两个根本不同的含义:

a) 将参数插入集合中,或者

b) 返回参数与接收者的算术和

另请注意,如果您的集合类实现了 IDisposable,那么如果 Add() 有可能抛出异常,或者如果任何输入到 Add() 的表达式都可能引发异常。

https://connect.microsoft.com/VisualStudio/feedback/details/654186/collection-initializers- Called-on-collections-that-implement-idisposable-need-to-失败时调用处理#

You need two things to make collection initializers work:

  1. Implement IEnumerable (non-generic version)
  2. Add() method that matches the collection initializer

Here's an example that looks like IDictionary:

class Program
{
    static void Main(string[] args)
    {
        MyClass obj = new MyClass()
        {
            {value1, value2},
            {value3, value4}
        };
    }
}

public class MyClass : IEnumerable
{
    public void Add(object x, object y)
    {

    }

    public IEnumerator GetEnumerator()
    {
    }
}

Note that the collection initializer code literally translates to this:

MyClass temp = new MyClass();
temp.Add(value1, value2);
temp.Add(value3, value4);
MyClass obj = temp;

Because of the temp variable, if any of the Add() calls generate an exception, the named variable (obj in this case) is never actually assigned. Interestingly, this also means that if MyClass were to implement IDisposable, then Dispose() would not get called on the constructed object when one of the Add() methods generates an error (I tested this to be sure).

Why require IEnumerable? Because that interface differentiates classes with Add for collections and classes with Add for calculations.

http://blogs.msdn.com/b/madst/archive/2006/10/10/what-is-a-collection_3f00_.aspx

[when you analyze classes with Add] you realize that there are essentially two fundamentally different meanings of the name “Add”:

a) Insert the argument into a collection, or

b) Return the arithmetic sum of the argument and the receiver

Also note that if your collection class implements IDisposable, then you should not use collection initializers if there is any chance that Add() will throw an exception or if any of the expressions being fed to Add() can throw an exception.

https://connect.microsoft.com/VisualStudio/feedback/details/654186/collection-initializers-called-on-collections-that-implement-idisposable-need-to-call-dispose-in-case-of-failure#

浅浅 2024-11-03 16:34:57

变量构造函数怎么样:

public class MyClass
{
    public MyClass() {}
    public MyClass(params object[] list) { ... }
}

How about a variable constructor:

public class MyClass
{
    public MyClass() {}
    public MyClass(params object[] list) { ... }
}
夜灵血窟げ 2024-11-03 16:34:57

默认值还不够好吗?

new MyClass {
   MyCol = {Value1, Value2, ... },
};

Isn't the default good enough ?

new MyClass {
   MyCol = {Value1, Value2, ... },
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文