在 C# 中使用集合初始值设定项创建新类
我有一个我创建的类。我想让类能够有一个集合初始值设定项。这是该类的一个示例:
public class Cat
{
private Dictionary catNameAndType = new Dictionary();
public Cat()
{
}
public void Add(string catName, string catType)
{
catNameAndType.Add(catName,catType);
}
}
我希望能够对该类执行类似的操作:
Cat cat = new Cat()
{
{"Paul","Black"},
{"Simon,"Red"}
}
这可以与不是字典和列表的类一起使用吗?
I have a class that I created. I would like to allow the class to be able to have a collection initializer. Here is an example of the class:
public class Cat
{
private Dictionary catNameAndType = new Dictionary();
public Cat()
{
}
public void Add(string catName, string catType)
{
catNameAndType.Add(catName,catType);
}
}
I would like to be able to do something like this with the class:
Cat cat = new Cat()
{
{"Paul","Black"},
{"Simon,"Red"}
}
Is this possible to do with classes that are not Dictionaries and Lists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了
Add
方法之外,该类还必须实现IEnumerable
接口。另请参阅:对象和集合初始化器(C# 编程指南)
In addition to an
Add
method, the class must also implement theIEnumerable
interface.See also: Object and Collection Initializers (C# Programming Guide)
是的,这是可能的。事实上,你几乎自己就解决了。使用这样的集合初始值设定项的要求是一个
Add
方法,该方法采用两个方法(您拥有),并且该类型实现 IEnumerable(您缺少该方法)。所以要让你的代码正常工作;使用类似的东西:Yes, it is possible. Actually, you almost solved it yourself. The requirements to use a collection initializer like that, is an
Add
method that takes two methods (which you have), and that the type implements IEnumerable (which you are missing). So to get your code to work; use something like:是的,正如其他答案中所述(只是为了提供更多详细信息),只需实现
IEnumerable
并使用一些Add()
方法:Yep, as stated in other answers (just to give more detail), just implement
IEnumerable<T>
and have someAdd()
method(s):