我如何允许 C# 添加另一种类型的结构来添加或添加相同类型的列表?
我有一个 List
我想在其中添加所有动物,即使我可以添加它们或添加它们整个列表。
我如何做一些他们允许添加 List
或 rat
的事情,他们不仅仅是我需要在其中添加任何类型的动物。
意味着我可以允许两者
List<animal> animal = new List<animal>();
animal.Add(new rat());
animal.Add(new List<Elephant>());
,我需要更多的东西,所有动物都是动物列表中找到的所有动物。我不需要计算所有对象,我需要计算单独添加或添加整个列表的每个动物。
谁能解释一下 C# 中的代码。
i have a List<animal>
where i want to add all animal their even i can add them or add them whole list.
how i can do something that they allow to add the List<rat>
or rat
their is not only one i need to add any type of animal in it.
means i can allow both
List<animal> animal = new List<animal>();
animal.Add(new rat());
animal.Add(new List<Elephant>());
i need a thing more that all animal is all animal found in animal list. i not need to count all object i need to count Every animal who add seprately or add whole list.
Can someone explain the code in C#.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,如果您愿意添加的类型没有共同的基本父级,则您不能使用通用列表。您可以使用允许存储任何类型的 ArrayList 。
更新:
如果
Rat
和Elephant
都派生于Animal
,你总是可以这样做,并且在 .NET 4.0 中,由于通用协方差,你也可以这样做:
但是以前版本的框架中没有。
Of course if the types you are willing to add don't have a common base parent you cannot use a generic list. You might use an ArrayList which allows for storing any types.
UPDATE:
If
Rat
andElephant
both derive fromAnimal
you can always doAnd in .NET 4.0 thanks to generic covariance you can also do:
but not in previous versions of the framework.
对于两种不同动物的示例,我认为动物的基类是有意义的,并为大象和动物派生了一个单独的类。一种不太新颖的方法是创建一个通用的对象列表,但也是可行的。不确定您的项目是什么,因此根据情况,您需要选择要使用的实现。将每个对象添加到通用列表中,并在使用 GetType() 方法之前检查其类型。
这是使用派生类的示例。您可以将基类更改为接口或抽象类,如上所述。我将很快提供一个使用通用对象的示例。
For your example with two different kinds of animals, I think a base class of animal makes sense, and derive a separate class for Elephant and Animal. A less novel approach, though doable is creating a generic list of objects. Not sure what your project is, so depending on the situation, you'll need to choose the implementation to use. Add each object to the generic list and check the type before using it with GetType() method.
Here's an example of using derived class though. You could change the base class to be an interface or abstract class as discussed above. I'll provide an example shortly for using generic objects.
这是使用对象列表的示例。我建议不要这种实现,因为通常基/抽象/接口类和派生类更干净,尽管我见过需要这样的情况。
Here's an example with using a list of objects. I'd advise against this implementation, as generally a base/abstract/interface class and derived classes is cleaner, though I have seen cases where something like this is required.