我正在使用泛型,并且在具有两个泛型参数的方法中尝试将对象强制转换为接口(interface),但这是行不通的。下面的代码演示了问题:
private void GenericMethod<T, U>()
where T : Block
where U : IBlock
{
var list = new List<T>();
// this casting works
var item = new Block();
var iItem = (IBlock)item;
foreach (var l in list)
{
// this doesn't compile
var variable = (U)l;
}
}
这里 Block 是一个类, IBlock 是这个类实现的接口(interface)。
为什么类型转换 (U)l 失败?我该怎么做?
最佳答案
如果 T 继承自 Block,U 继承自 IBlock,这并不意味着即使 Block 继承自 IBlock,T 也会继承自 U。例如:
public class TBlock : Block
{
public void NewMethod() {}
}
public interface UIBlock : IBlock
{
void AnotherNewMethod();
}
为了使这个例子工作,你必须改变
where T : Block
where U : IBlock
到
where U : IBlock
where T : Block, U
确保 T 继承自 U。
关于c# 无法将对象强制转换为具有多个泛型参数的方法中的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25068105/