Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.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#_Generics_Interface - Fatal编程技术网

类声明中泛型参数的C#复制

类声明中泛型参数的C#复制,c#,generics,interface,C#,Generics,Interface,我今天正在玩C#泛型和接口,并尝试实现的经典定义。以下是我的最佳尝试(仅用于练习): 接口IVertex { 字符串名称{get;set;} } 接口边缘,其中V:IVertex { V来自{get;set;} V到{get;set;} } 接口I图,其中E:IEdge,其中V:IVertex { IList顶点{get;} IList边{get;} } 类顶点:IVertex { 公共字符串名称{get;set;} 公共顶点(字符串名称) { 名称=名称; } } 类边:IEdge,其中V:I

我今天正在玩C#泛型和接口,并尝试实现的经典定义。以下是我的最佳尝试(仅用于练习):

接口IVertex
{
字符串名称{get;set;}
}
接口边缘,其中V:IVertex
{
V来自{get;set;}
V到{get;set;}
}
接口I图,其中E:IEdge,其中V:IVertex
{
IList顶点{get;}
IList边{get;}
}
类顶点:IVertex
{
公共字符串名称{get;set;}
公共顶点(字符串名称)
{
名称=名称;
}
}
类边:IEdge,其中V:IVertex
{
来自{get;set;}的公共V
公共V到{get;set;}
公共边缘(V从,V到)
{
From=From;
To=To;
}
}
类图:IGraph其中E:IEdge其中V:IVertex
{
公共IList顶点{get;}=new List();
公共IList边{get;}=new List();
}
但我认为我做错了什么,因为在以下用法中:

var a = new Vertex("A");
var b = new Vertex("B");
var c = new Vertex("C");

var x = new Edge<Vertex>(a, b);
var y = new Edge<Vertex>(b, c);
var z = new Edge<Vertex>(c, a);

var graph = new Graph<Vertex, Edge<Vertex>>()
{
    Vertices = { a, b, c },
    Edges = {x, y, z}
};
var a=新顶点(“a”);
var b=新顶点(“b”);
var c=新顶点(“c”);
var x=新边(a,b);
var y=新边(b,c);
var z=新边(c,a);
变量图=新图()
{
顶点={a,b,c},
边={x,y,z}
};

我需要指定通用参数
Vertex
(在
new Graph()
行)两次…

如果没有更多上下文,就不清楚您的约束和要求是什么。但是,根据您试图完成的任务,可能需要使用您当前拥有的语法,以确保正确声明您的
IList

您也可能不需要
Graph
类具有确切的
IEdge
类型。如果是,那么您可以这样声明:

class Graph<V> : IGraph<V, IEdge<V>> where V : IVertex
{
    public IList<V> Vertices { get; } = new List<V>();
    public IList<IEdge<V>> Edges { get; } = new List<IEdge<V>>();
}

这完全取决于您实际希望如何使用这些类型。

这没有错(或者至少本身没有错)。编写
Edge:IEdge
这样可以省略泛型参数(这样就可以省略
Edge
类级别的类型参数)。问题是什么?@Alejandro我认为问题更多的是关于graph类的模板(或泛型)专门化
class Graph<V> : IGraph<V, IEdge<V>> where V : IVertex
{
    public IList<V> Vertices { get; } = new List<V>();
    public IList<IEdge<V>> Edges { get; } = new List<IEdge<V>>();
}
IList<Edge<Vertex>> list = graph.Edges;