c# - 如何指定和使用真实的接口(interface)?

标签 c#

是否可以指定必须用接口(interface)实现方法的真实接口(interface)?` 或者这如何工作我想要的:

public interface IGraph
{
    void addEdge(IGraphVertex a, IGraphVertex b);
}

public interface IGraphVertex
{

}

// problematic code


public class Graph2d : IGraph
{
    public void addEdge(Graph2dVertex a, Graph2dVertex b)
    {

    }
}

public class Graph2dVertex : IGraphVertex
{

}

我得到的错误是 Graph2d 没有实现 addVertex(IGraphVertex a, IGraphVertex b);

最佳答案

你想要一个通用接口(interface):

public interface IGraphVertex
{

}

public interface IGraph<T>
    where T: IGraphVertex
{
    void addEdge(T a, T b);
}

然后:

public class Graph2dVertex : IGraphVertex
{

}

public class Graph2d : IGraph<Graph2dVertex>
{
    public void addEdge(Graph2dVertex a, Graph2dVertex b)
    {

    }
}

关于c# - 如何指定和使用真实的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141004/

相关文章:

c# - 无法将枚举绑定(bind)到组合框 wpf mvvm

c# - 将 DataGridView 的 DataSource 设置为 null/false 会删除 DataGridView 的所有默认设置

c# - 从 Javascript 调用 Web 服务(传递参数和返回数据集)

java - 在 Java 中,什么类型表示函数或带有 3 个参数的 lambda 表达式?

c# - 如何在 XNA 中播放动态声音?

c# - 在 .NET 中比较两种 RGB 颜色的最快方法是什么?

c# - 为什么使用 ConfigurationManager 与读取自定义配置文件?

c# - IAsyncEnumerable 的传递?

c# - 使用存储库模式 c# 检查用户登录

c# - 如何添加额外的 Dictionary 对象