通用类型接口强制转换为特定接口

时间:2017-11-16 20:31:59

标签: c# .net

如何将具有泛型类型的接口转换为通用接口?

假设我们有以下接口/对象:

public interface IAction : IAction<object> { }
public interface IAction<T>
{
    T PerformAction();
}
public class SomeAction : IAction<string>
{
    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    public int PerformAction()
    {
        return 100;
    }
}

然后,如果我们尝试在控制台应用程序中对其进行编码:

List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));

我们如何解决错误&#34;无法转换为“SomeAction&#39;到&#39; IAction&#39;&#34;?

1 个答案:

答案 0 :(得分:2)

您的继承层次结构没有意义,您应该IAction<T>扩展IAction而不是相反。

您还需要添加要调用IAction的任何常用方法,如果方法具有相同的名称和参数,则使用显式接口实现来实现它们。它是在通用接口实现上,您将调用该方法。

public interface IAction
{
    object PerformAction();
}
public interface IAction<T> : IAction
{
    new T PerformAction();
}
public class SomeAction : IAction<string>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }

    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }
    public int PerformAction()
    {
        return 100;
    }
}

致电代码

List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));