如何创建一个类似数组的 C# 构造函数,允许“new MyClass() { obj1, obj2, obj3 };”
我正在尝试创建一个类,它接受类似于字典、列表或数组的构造函数,您可以在其中使用对象的文字集合创建对象,尽管我一直无法找到如何创建这样的构造函数,如果可能的话。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要使集合初始值设定项起作用,您需要做两件事:
IEnumerable
(非泛型版本)Add()
方法一个类似于 IDictionary 的示例:
下面 集合初始值设定项代码字面上翻译为:
由于临时变量,如果任何
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
另请注意,如果您的集合类实现了 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:
IEnumerable
(non-generic version)Add()
method that matches the collection initializerHere's an example that looks like IDictionary:
Note that the collection initializer code literally translates to this:
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 ifMyClass
were to implementIDisposable
, thenDispose()
would not get called on the constructed object when one of theAdd()
methods generates an error (I tested this to be sure).Why require
IEnumerable
? Because that interface differentiates classes withAdd
for collections and classes withAdd
for calculations.http://blogs.msdn.com/b/madst/archive/2006/10/10/what-is-a-collection_3f00_.aspx
Also note that if your collection class implements
IDisposable
, then you should not use collection initializers if there is any chance thatAdd()
will throw an exception or if any of the expressions being fed toAdd()
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#
变量构造函数怎么样:
How about a variable constructor:
默认值还不够好吗?
Isn't the default good enough ?