c# - 泛型通配符或类似的东西

标签 c# generics

目前我正在做一项作业,我必须创建一个用 C# 实现的自定义用户控件。我主要有 java 背景,所以我不知道我想做的事情在 C# 中是否可行 - 如果不行,有人可以给我提供一个链接或替代方法,我可以在 C# 中完成同样的事情。

public abstract class Graph<T,U>
where T : Configuration.GraphConfiguration
where U : Representatives.GraphRepresentative
{
    public abstract void Draw(Graphics g);
}

public class LineGraph: Graph<LineGraphConfiguration,LineGraphRepresentative>{

    public void draw(Graphics g){

    } 

}

//"Graph" is not valid since the type params <T,U> are not specified..
//However, I cannot supply them since I don't know until runtime what 
//they are. In java just "Graph" or Graph<?,?> would be valid and I  need
//something similar.
public class MyCustomControl: UserControl{
    Graph currentGraph;

    override OnPaint(PaintEventArgs e){
       currentGraph.Draw(e.Graphics);
    }
}

所以基本上我需要一种类型或某种方式来保存 LineGraph 和任何其他类型的图表 - 例如稍后的 BarGraph - 即使类型参数不同。

最佳答案

由于您的代码显示您不需要这些泛型类型来绘制整个图,我看到您可以轻松解决定义非泛型接口(interface)的问题:

public interface IGraph
{
     void Draw(Graphics g);
}

...并且您的抽象类可以实现它:

public abstract class Graph<T,U> : IGraph
where T : Configuration.GraphConfiguration
where U : Representatives.GraphRepresentative
{
    public abstract void Draw(Graphics g);
}

...所以这意味着您现在可以使用 IGraph 来键入您的类字段:

public class MyCustomControl: UserControl{
    IGraph currentGraph;

    override OnPaint(PaintEventArgs e){
       currentGraph.Draw(e.Graphics);
    }
}

关于泛型、通配符...

至少在 .NET 中,引入了泛型以尽可能地强制执行强类型,并避免大量强制转换损害性能和可维护性。这不是可以绕过的东西。

顺便说一句,C# 在接口(interface)和委托(delegate)上具有协变 和逆变。我建议您查看以下资源:

关于c# - 泛型通配符或类似的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36420404/

相关文章:

c# - 降噪库?

c# - 检测到 ContextSwitchDeadlock

java - 使用参数化类型实现 guice Provider

java - 类和类的区别<?>

c# - 将通用类绑定(bind)到特定接口(interface)

c# - AutoCAD eNotOpenForWrite

c# - .NET Core TestServer 返回状态 200 而不是 404 以将请求发送到不存在的路径

c# - 是否可以使用反射获取当前正在执行的类名?

C# 失败的协变转换

C# 使用泛型和接口(interface)实现