Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建从抽象父类继承的不同类型的集合_C#_Events_Inheritance_Collections - Fatal编程技术网

C# 创建从抽象父类继承的不同类型的集合

C# 创建从抽象父类继承的不同类型的集合,c#,events,inheritance,collections,C#,Events,Inheritance,Collections,很可能有比我在标题中的建议更好的方法来解决这个问题。问题是: abstract class BaseClass { abstract public void DoSomething(); } class ChildClass : BaseClass { public override DoSomething(); } class OtherClass { //Here is what I want to do for two elements

很可能有比我在标题中的建议更好的方法来解决这个问题。问题是:

abstract class BaseClass 
{
      abstract public void DoSomething();
}

class ChildClass : BaseClass 
{
      public override DoSomething();
}

class OtherClass
{
    //Here is what I want to do for two elements
      ChildClass foo = new ChildClass();
      SomeOtherChildClass bar = new SomeOtherChildClass();
      foo.DoSomething();
      bar.DoSomething();
}
我想做更多的元素。我不想创建它们自己的变量,也不想为每个子类创建单独的列表。我实际上不想知道有哪些子类,只要它们继承基类并具有DoSomething()。所以我可以做一些类似的事情:mycollection.ForEach(I=>I.DoSomething());到

我想我需要一些相当宽松的收藏。我想到了IEnumable和对新元素进行封装,但是当基类是抽象的时候,当然不能这样做


另一种选择(我能想到)是使用事件。但是OtherClass可能有多个实例,我不想触发我不应该触发的事情。也许我错了,但我对事件知之甚少。

您只需要一个基类类型的列表,例如

List<BaseClass> myCollection
你可以

myCollection.Foreach(i => i.DoSomething());
myCollection.Foreach(i => i.DoSomething());