c# - 使用通用接口(interface)配置通用工作流程

标签 c# .net generics .net-4.5

我们最近在数据收集程序中遇到了一个问题。我们使用通用接口(interface)来拥有一个通用的工作流程,该工作流程可以通过配置中的具体实现轻松针对不同的数据输入进行定制。最近对丢失数据错误的修复大致如下所示:

[TestFixture]
internal class GenericsTest
{
    [Test]
    public void Config()
    {
        new Collector(new Search());
    }
    internal class Collector
    {
        public Collector(Clues<Where, What> foo)
        {

        }
    }
    internal interface Clues<T, P>
    {

    }
    internal class Search : Clues<Where, Item>
    {

    }
    internal class Where
    {

    }
    internal class Item : What
    {

    }

    internal interface What
    {

    }

}

配置正在使用特定搜索初始化特定收集器。 Collector 本身只需要一个带有具体类 Where 和接口(interface) What 作为参数的通用接口(interface)。 Search 类应该通过使用 Where 类和本身实现 What 接口(interface)的 Item 类实现通用 Clues 接口(interface)来满足这些期望。 相反,Search 的初始化失败,因为它无法将具体实现与一般期望联系起来。

Error   CS1503  Argument 1: cannot convert from 'UnitTest.GenericsTest.GenericsTest.Search' to 'UnitTest.GenericsTest.GenericsTest.Clues<UnitTest.GenericsTest.GenericsTest.Where, UnitTest.GenericsTest.GenericsTest.What>'

我们尝试转换为所需的类型,但它只是将错误转移到了运行时。

一般概念是,工作流尽可能保持通用,配置会处理所有特定要求。所需的具体方法应该在项目类中引入并隐藏在接口(interface)后面以避免不必要的困惑。

有没有一种特定的方法可以在 C# 中编写这样的实现?

最佳答案

您必须更改Clues 的定义 并使用 covariance

Covariance: Enables you to use a more derived type than originally specified

internal interface Clues<T, out P>

编辑

如果您不能更改接口(interface),那么也许您可以更改 Collector 类以使用带有约束的泛型:

internal class Collector<TWhere,TWhat> where TWhere:Where where TWhat:What
{
    public Collector(Clues<TWhere, TWhat> foo)
    {

    }
}

然后您必须准确指定您将要使用的类型:

public void Config()
{
    new Collector<Where,Item>(new Search());
}

关于c# - 使用通用接口(interface)配置通用工作流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44266310/

相关文章:

.net - .NET 紧凑框架的 GPS 库

c# - SignalR 和 WinRT 客户端 : Don't call Wait() on Start()

vb.net - 在运行时动态创建类

Java 泛型 : the type parameter T is hiding the type T

C# 模式与属性的操纵值匹配

c# - NHibernate QueryOver 中的排序和分组

c# - 接口(interface)实例

c# - 在 C# 中组合 ViewStates 或在 C# 中组合泛型列表

c# - 设计具有可以使用附加属性扩展的实体的应用程序的最佳方法是什么?

c# - ContentControl.Template 和 ContentControl.ContentTemplate 有什么区别