簡體   English   中英

c#無法在具有多個通用參數的方法中將對象強制轉換為接口

[英]c# cannot cast object to interface in a method with multiple generic parameters

我正在使用泛型,並且在具有兩個泛型參數的方法中嘗試將對象強制轉換為接口,這是行不通的。 下面的代碼演示了問題:

    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是由該類實現的接口。

為什么鑄造(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。

雖然可以將T轉換為IBlock,但是就規則而言,您不知道它是否可以轉換為U-U實現IBLock,但可以是任何類型。

您可以投射迭代器。 https://dotnetfiddle.net/FgKdL8

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
    }

    private void GenericMethod<T, U>() 
        where T : Block
        where U : IBlock
    {
        var list = new List<U>();

        // this casting works
        var item = new Block();
        var iItem = (IBlock)item;

        // cast your iterator
        foreach (U l in list)
        { 

        }
    }

    public interface IBlock
    {}
    public class Block : IBlock
    {}
}

如果可以保證T將繼承U,則可以將該約束添加到聲明中:

where U : IBlock where T : Block, U

如果您希望函數仍然以任何一種方式工作,但是如果可能的話,將其強制轉換為U(我真的無法想象為什么要這么做,但是...),您可以這樣做:

public GenericMethod<T, U>()
    where T : Block
    where U : class, IBlock // must be a class to use the `as` operator 
{
    // ... 
    var variable = item as U;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM