c#无法在具有多个通用参数的方法中将对象强制转换为接口

lek*_*kso 1 c# generics casting

我正在玩Generics并且在一个带有两个通用参数的方法中尝试将一个对象强制转换为接口,但这不起作用.以下代码演示了问题:

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里的Block是一个类,IBlock是这个类实现的接口.

为什么铸造(U)l失败?我该怎么做?

Jam*_*ran 6

如果T继承自Block,而来自IBlock的U,则并不意味着即使Block继承自IBlock,T也将从U继承.例如:

public class TBlock : Block
{
   public void NewMethod() {}
}

public interface UIBlock : IBlock
{
   void AnotherNewMethod();
}
Run Code Online (Sandbox Code Playgroud)

要使此示例有效,您必须进行更改

where T : Block
where U : IBlock
Run Code Online (Sandbox Code Playgroud)

where U : IBlock
where T : Block, U
Run Code Online (Sandbox Code Playgroud)

确保T继承自U.