C#将类派生为数组

C#将类派生为数组,c#,oop,C#,Oop,我在这里找不到我的问题,所以我只是问,希望这是一个新问题 假设我有一个名为base的基类,并且base中有一个名为Reset的函数,我将定义base类的数组,但每次我想重置所有数组项时,我必须迭代所有元素Reset函数 我的问题是:是否有一种方法可以将Base类派生为Child类,该类由Base数组组成,并在Child中创建一个ResetAll函数来迭代数组的所有Reset函数 或者创建一个将触发所有重置函数的函数。您不需要创建派生类。基本上,您不希望遍历数组中的所有基本对象,并在需要重置它们时

我在这里找不到我的问题,所以我只是问,希望这是一个新问题

假设我有一个名为base的基类,并且base中有一个名为Reset的函数,我将定义base类的数组,但每次我想重置所有数组项时,我必须迭代所有元素Reset函数

我的问题是:是否有一种方法可以将Base类派生为Child类,该类由Base数组组成,并在Child中创建一个ResetAll函数来迭代数组的所有Reset函数


或者创建一个将触发所有重置函数的函数。

您不需要创建派生类。基本上,您不希望遍历数组中的所有基本对象,并在需要重置它们时对它们调用Reset方法

您所需要的只是一个Base数组的扩展方法

您可以在

对于您的情况,您可以创建如下扩展方法

public static class BaseExtensions
{
    public static void ResetAll(this Base[] baseArray)
    {
        foreach(var baseItem in baseArray)
        {
            baseItem.Reset();
        }
    }
}
//Let say you have a an array of base as following.
Base[] items = new Base[2];
items[0] = new Base();
items[1] = new Base(); 

//You can reset them as following.
items.ResetAll(); //This is the ResetAll extension method created above.
您可以按如下方式使用上述方法

public static class BaseExtensions
{
    public static void ResetAll(this Base[] baseArray)
    {
        foreach(var baseItem in baseArray)
        {
            baseItem.Reset();
        }
    }
}
//Let say you have a an array of base as following.
Base[] items = new Base[2];
items[0] = new Base();
items[1] = new Base(); 

//You can reset them as following.
items.ResetAll(); //This is the ResetAll extension method created above.

这将帮助您解决问题。

Well ResetAll()应该是列表类数组的一部分。关键字
This
在定义扩展方法时可能很有用。;-)很好地抓住了“谜”。我犯了一个愚蠢的错误。。。。谢谢你指出。我改正了错误。