有
public interface IGeneric<T>{}
public class Student{}
public class Teacher{}
这个有可能
public class ConcreateClass : IGeneric<Student>, IGeneric<Teacher>{}
这是不可能的
public class GenericClass<T1, T2> : IGeneric<T1>, IGeneric<T2> {}
因为GenericClass<String, String> instance;
会导致两个接口实现的歧义。但是为什么这是不可能的
public class GenericClassWithTypeConstraints<T1, T2> : IGeneric<T1>, IGeneric<T2>
where T1 : Student
where T2 : Teacher
{}
因为 T1 和 T2 不能属于同一类?(编译器错误与没有类型约束的情况相同)
在为什么这会导致 CS0695中编辑
“Soner Gönül”, 提出了一个解决方法,使用两个级别的类继承,如下所示:
public interface IGeneric<T> { String Name { get; } }
public class Student{}
public class Teacher{}
public class GenericClassBase<T1> : IGeneric<T1>
where T1 : Student
{ String IGeneric<T1>.Name { get { return "Generic class of Student"; } } }
public class GenericClassDerived<T1, T2> : GenericClassBase<T1>, IGeneric<T2>
where T1 : Student
where T2 : Teacher
{ String IGeneric<T2>.Name { get { return "Generic class of Teacher"; } } }
像这样的代码然后产生预期的结果
GenericClassDerived<Student, Teacher> X = new GenericClassDerived<Student, Teacher>();
Console.WriteLine(((IGeneric<Student>)X).Name); //outputs "Generic class of Student"
Console.WriteLine(((IGeneric<Teacher>)X).Name); //outputs "Generic class of Teacher"