C# 如何在具有不同类型的类型上调用共享成员?

C# 如何在具有不同类型的类型上调用共享成员?,c#,.net,winforms,design-patterns,C#,.net,Winforms,Design Patterns,我有不同的自定义Winforms控件集,这些控件都是从控件派生的,例如: CalculatorPanel, GraphPanel, DisplayPanel, etc : Control 我使用一个表单来显示其中一个或多个集合,具体取决于用户希望看到的内容 他们都有一名成员,名为: Input 如果类型不同,例如: CalculatorInput, GraphInput, DisplayInput, etc. 如何将它们存储在列表或其他集合中,以便调用输入属性而不会出现任何问题 我是否应该

我有不同的自定义Winforms控件集,这些控件都是从控件派生的,例如:

CalculatorPanel, GraphPanel, DisplayPanel, etc : Control
我使用一个表单来显示其中一个或多个集合,具体取决于用户希望看到的内容

他们都有一名成员,名为:

Input
如果类型不同,例如:

CalculatorInput, GraphInput, DisplayInput, etc.
如何将它们存储在列表或其他集合中,以便调用输入属性而不会出现任何问题

我是否应该为每个应用程序使用公共接口?那么它必须是通用的。如何指定类型

现在,我使用类似这样的方法来添加/删除控件:

Panels = Dictionary <Enum, Control> ...
Panels.Add (PanelType.Calculator, new CalculatorInput ().Controls);
...
但是当我需要在运行时设置它们的输入属性时,我该如何设置它们呢。因此,如果用户切换到GraphPanel,我希望能够在我将其控件添加到表单后立即设置其输入

有没有设计模式或技术来解决这个问题

编辑:每个输入类型(无方法)的属性如下所示:

CalculatorInput:
.Result
.LastOperation
...

GraphInput:
.Result
.SelectedNode
...

DisplayInput:
.Result
.CurrentColor
...
class CalculatorPanel
{
    CalculatorInput Input
}

class GraphPanel
{
    GraphInput Input
}

class DisplayPanel
{
    DisplayInput Input
}
基本上,这些输入只是要绑定到适当UI的类型。因此,如果UI有一些属性,它们将绑定到这些输入,这就是为什么当我分配新输入时,UI将自动更新

编辑2:

所以所有这些输入都是独立的,没有继承,等等

但在适当的卷展栏中定义如下:

CalculatorInput:
.Result
.LastOperation
...

GraphInput:
.Result
.SelectedNode
...

DisplayInput:
.Result
.CurrentColor
...
class CalculatorPanel
{
    CalculatorInput Input
}

class GraphPanel
{
    GraphInput Input
}

class DisplayPanel
{
    DisplayInput Input
}

由于输入本质上是独立的,因此它们可以为少量的公共功能实现一个接口,但可能不会实现太多(了解输入类成员的数据类型会有所帮助)。要访问非通用功能(这是大多数输入对象),您仍然需要额外的逻辑才能正常工作:

if (currentControl is CalculatorPanel)
{
    CalculatorInput input = (currentControl as CalculatorPanel).Input;
    // ...
}
else if (currentControl is GraphPanel)
{
}
etc.

我认为您需要的是一个所有类都将从中继承的输入接口

public interface MyInputInterface
{
        void YourInputFunction();
}

public class CalculatorPanel : Control, MyInputInterface
{
   ..
   ..

   void MyInputInterface.YourInputFunction()
   {
       // do your code specific to calculator panel here
   }
}

public class GraphPanel : Control, MyInputInterface
{
   ..
   ..

   void MyInputInterface.YourInputFunction()
   {
       // do your code specific to graph panel here
   }
}
然后,您可以构建实现MyInputInterface的任何内容的列表

public List<MyInputInterface> MyInputList = new List<MyInputInterface>();
public List MyInputList=new List();

并根据需要使用该列表。。。接口是任何对象的契约,利用它来保证它具有相关的属性、字段、函数等。

接口的指针允许来自dispirit类型的公共调用机制的契约。为什么调用接口方法在这里是一个糟糕的设计点。什么,这就是接口的整个点,它们显然属于同一个超类型,即“输入”。OP没有明确说明输入是否共享公共功能,因此考虑到类的名称,我假设它们不共享(计算器输入与图形输入如何相似?)。谢谢Jon,我实际上使用的方法与你的方法类似,只是不知道是否有更好的方法。谢谢。即使在.Result的情况下,输入成员也是不同的。因此,类型不同。因此,基本上它们就像苹果和橘子一样,只是它们都是通过面板的.input属性访问的。这就是为什么我我想知道是否有更好的方法。如果接口是显式实现的,那么您需要转换到该接口才能看到“YourInputFunction”。不,只需调用——在本例中为object.YourInputFunction。每个类实现将知道如何对其自己的控件和环境进行操作……除非您返回一个通用的“object”这需要稍后进行cast()编辑。列表已经知道它是一个控件,该控件将具有可用的函数。如果您正在处理大量对象,它们将被分配给一个具有接口类型的变量。请概述每个输入类的属性/方法,好吗?