我对C#中的泛型有疑问,这是代码:
public interface IMyInterface
{
void fun(ClassB b);
}
class ClassA: IMyInterface
{
void IMyInterface.fun(ClassB b)
{
//Console.WriteLine(a);
b.fun();
}
}
public class ClassB
{
public void fun()
{
Console.WriteLine("111");
}
}
class ClassZ<T, K>
where T: IMyInterface, new()
where K: new()
{
public T objT;
public K objK;
public void funB()
{
objT = new T();
objK = new K();
objT.fun(objK); //Error, cannot convert from 'K' to 'ConsoleApp1.ClassB'
}
}
class Program
{
static void Main(string[] args)
{
ClassZ<ClassA, ClassB> objB = new ClassZ<ClassA, ClassB>();
objB.funB();
}
}
无法从“ K”转换为“ ConsoleApp1.ClassB”
T和K都是某个类,我想调用objT.fun(objK),objK作为参数。
有任何建议吗?谢谢!
答案 0 :(得分:2)
方法
void IMyInterface.fun(ClassB b)
期望对类型为ClassB
的对象的引用。 K
参数化类型不能保证这一点。
您可以通过替换以下通用约束来解决此问题
where K: new()
与此一起
where K: ClassB, new()
答案 1 :(得分:1)
发生这种情况是因为您的接口 MyInterface 期望使用ClassB类型的对象。 您可以通过将K定义为ClassZ中ClassB的类型来解决此问题:
class ClassZ<T, K>
where T: IMyInterface, new()
where K: ClassB, new()
{
public T objT;
public K objK;
public void funB()
{
objT = new T();
objK = new K();
objT.fun(objK);
}
}
答案 2 :(得分:0)
您需要让K
约束为ClassB
where K : ClassB,new()
代替
where K : new()