【问题标题】:Method generics different interface方法泛型不同的接口
【发布时间】:2019-08-22 15:24:28
【问题描述】:

为什么我不能将泛型方法与这样的接口一起使用?

我的参数接口

public interface IBaseParam {
    string Name { get; }
}


public interface IComplexParam : IBaseParam {
    string P1 { get; }
    string P2 { get; }
}

使用通用接口的类

public interface ILauncherCommand {
    void launch<T>(T parameters) where T : IBaseParam;
}



public class BaseCommand : ILauncherCommand {
    string Name { get; }

    public void launch<T>(T parameters) where T : IBaseParam {

    }
}



public class ComplexCommand : ILauncherCommand {
    string Name { get; }

    public void launch<T>(T parameters) where T : IComplexParam {

    }
}

ComplexCommand.launch 是编译器显示问题 (CS0425) 的地方。 IComplexParam 继承自 IBaseParam,因此合约必须有效。

只有声明泛型类才能编译,但我想使用泛型方法而不是完整的泛型类

下面的代码可以工作,但是是一个泛型类

public interface ILauncherCommand<T> where T : IBaseParam {
    void launch(T parameters);
}



public class BaseCommand : ILauncherCommand<IBaseParam> {
    string Name { get; }

    public void launch(IBaseParam parameters) {

    }
}



public class ComplexCommand : ILauncherCommand<IComplexParam> {
    string Name { get; }

    public void launch(IComplexParam parameters) {

    }
}

【问题讨论】:

    标签: c# methods interface


    【解决方案1】:

    泛型方法强制您使用 Invariant 类型,这意味着您必须准确提供您指定的内容。

    您正在寻找的是启用协方差类型以允许使用更多派生类型。这只能在班级级别完成:

    请注意,&lt;in T&gt; 是指定协方差的方式。

    public interface ILauncherCommand<in T> where T : IBaseParam
    {
        void launch(T parameters);
    }
    
    public class BaseCommand<T> : ILauncherCommand<T> where T : IBaseParam  
    {
        string Name { get; }
    
        public void launch(T parameters)
        {
        }
    }
    
    public class ComplexCommand<T> : ILauncherCommand<T> where T : IComplexParam
    {
        string Name { get; }
    
        public void launch(T parameters)
        {
        }
    }
    

    在这种特定情况下,请注意 &lt;in &gt; 是可选的,因为协方差是自动的。

    您可以在此处获取更多信息:covariance and contravariance

    【讨论】:

    • 好的,所以我的第二个实现,泛型类,(参见 OP)是唯一可用的。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 2012-03-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多