Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.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语言中的实现#_C#_Generics_Interface_Constraints - Fatal编程技术网

C# 强制通用接口在C语言中的实现#

C# 强制通用接口在C语言中的实现#,c#,generics,interface,constraints,C#,Generics,Interface,Constraints,是否存在强制通用定义约束以实现“通用接口”。。。也就是说,我希望该类支持传递接口和约束接口的泛型类,以便该类实现该接口。例如,如果我说: MyGenericClass<IMyInterface, MyImplementation>.DoSomething(); MyGenericClass.DoSomething(); 这应该受到约束,以便MyImplementation实现IMyInterface 据我所知,这可以通过 public class Dynamic_Loader&l

是否存在强制通用定义约束以实现“通用接口”。。。也就是说,我希望该类支持传递接口和约束接口的泛型类,以便该类实现该接口。例如,如果我说:

MyGenericClass<IMyInterface, MyImplementation>.DoSomething();
MyGenericClass.DoSomething();
这应该受到约束,以便MyImplementation实现IMyInterface

据我所知,这可以通过

public class Dynamic_Loader<T, S> where S: T
公共类动态\u加载程序,其中S:T
现在,有没有强迫T成为一个接口

编辑:这样做的目的是:

private static List<T> interfaceList = new List<T>();

public static List<T> InterfaceList {get { return interfaceList;}}

public static void Add(S input) { interfaceList.Add(input);}
private static List interfaceList=new List();
公共静态列表接口列表{get{return InterfaceList;}}
公共静态void Add(S输入){interfaceList.Add(输入);}
并且列表仅限于接口(因为它应该返回某些接口的实现)

例如:

    public class Test<T, V>
    where T : V
    where V : IEnumerable<int>
    {
    }
公共类测试
T:V在哪里
其中V:IEnumerable
{
}

您的意思是,也可以像
中的T:interface
一样对
T
施加约束吗?

如果是,那么:几乎涵盖了您的选项

我相信你所拥有的是最接近的

出于好奇,您希望将
T
约束为接口的原因是什么

或者您的意思是,是否可以对
T
施加约束,以实现特定的接口?


如果是这样,那么yes:只需使用两个
where
子句(例如,
where S:T where T:U
)。

您可以在运行时而不是编译时执行类似操作

public class Test<T> where T : class
{
  public Test()
  {
    Type t = typeof( T );
    if( !t.IsInterface )
      throw new ArgumentException( "T must be an interface type" );
  }
}
公共类测试,其中T:class
{
公开考试()
{
类型t=类型(t);
如果(!t.i接口)
抛出新ArgumentException(“T必须是接口类型”);
}
}

哦,我想说的是:公共静态列表接口列表=新列表;公共静态无效添加输入;是的,如果T只是一个基类,但客户端应该得到接口,而不是基类,那么它也会起作用。
public class Test<T> where T : class
{
  public Test()
  {
    Type t = typeof( T );
    if( !t.IsInterface )
      throw new ArgumentException( "T must be an interface type" );
  }
}