c# 无法将对象强制转换为具有多个泛型参数的方法中的接口(interface)

标签 c# generics casting

我正在使用泛型,并且在具有两个泛型参数的方法中尝试将对象强制转换为接口(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/

相关文章:

java - 覆盖方法

c++ - "lossless" float 到字节的转换

c# - Xamarin 中不显示 ImagePicker

c# - 找不到源类型 'System.Data.Entity.DbSet' 的查询模式的实现

swift - 如何为通用函数过滤或有多个选项?

JAVA 和泛型类型问题

c# - 是否可以在 net core 中加载特定于平台的 .net 库?

c# - 点网核心 3.1 : How to use AddJsonFile with absolute path to file?

r - 将字符串转换为 R 中的函数

java - 类型转换可以作为适配器设计模式的一个例子吗?