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# - 为什么这个具有类型约束的通用方法无法编译?

如果我包装我的对象,Golang 转换为自定义类型会失败

c# - List<string> 如何成为 AutoCompleteStringCollection

c# - Xamarin.Forms 上的混合固定元素和可滚动元素

c# - 另一台机器的时间

java - 为什么可以转换不同类型的 map ?

javascript - 将 javascript 变量 “11:00 AM” 转换为 c# 等效项,其中 SQL 为时间格式

c# - "Promote"泛型类型在 C# 中为 Nullable?

java - 为什么我不能将 T 类型转换为比较器中的另一个对象?