c# - 如何实现非泛型的泛型参数

标签 c# generics

我有一个带有两个通用参数的接口(interface),但其中一个参数应该由类实现提供。

public interface IA<T, U> { ... }
public class X<T> : IA<T, int> { ... }
public class Y<T> : IA<T, MyClass> { ... }

然而,另一个接口(interface)有一个方法接受IA 的实例。作为参数 - 但是,每个实例必须相同(同一个类可以采用倍数 X ,但它永远不会采用 Y ,反之亦然)。我试图把它作为一个通用的约束,但后来我有类似的东西

public interface IB<T, U, V> where U : IA<T, V> {
   void MyMethod(U value);
}
public class Z<T> : IB<T, X<T>, int> { ... }

我当然不想写那个参数V ,因为我无法为它选择一个值。参数U已经规定了 V 的值应该是多少!但是,我不能简单地删除 V ,因为那时我无法编写约束条件。


另一种解决方案是不使用约束:

public interface IB<T> {
   void MyMethod(IA<T> value);
}

但是这样一来,我就不能保证IB的执行了将只收到一个 IA 的实现(即,它将能够同时接收 XY,但它不应该)。


有什么方法可以避免创建通用参数 V在界面中IB (在第一个解决方案中)同时仍然相互排除 IA 的实现?编译器是否有任何特定原因无法推断 V 的类型并允许我只写 class Z<T> : IB<T, X<T>>或者这种情况只是在语言规范中没有预料到/被选择不实现?

最佳答案

您已经有足够的通用类型来限制 IB<T,U>.MyMethod()从收到两个XY .您只需将方法参数定义为接受特定类型。

    public interface IA<T,U> {}
    public class X<T> : IA<T,int> {}
    public class Y<T> : IA<T,string> {}

    public interface IB<T,U>
    {
        void MyMethod(IA<T,U> value);
    }

    IB<int,int> foo;
    X<int> a;
    Y<int> b;

    foo.MyMethod(a); // will compile
    foo.MyMethod(b); // will not compile

Is there any way to avoid the creation of the generic parameter V in the interface IB (in the first solution) while still mutually-excluding the implementations of IA? Is there any specific reason the compiler can't infer the type of V and allow me to write only class Z : IB> or this case just wasn't expected in the language specs/was chosen to not be implemented?

我不认为这就是 C# 中推理的工作方式。推断 U 的类型MyMethod会这样写。

    public interface IB<T>
    {
        void MyMethod<U>(IA<T,U> value);
    }

    IB<int> foo = null;
    X<int> a;
    foo.MyMethod(a); // int type is inferred by compiler

你仍然需要使用 IA<T,U>在你的IB界面。我认为没有简单的方法可以解决这个问题。

关于c# - 如何实现非泛型的泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24748679/

相关文章:

c# - 使用 Rally REST API,如何查询并返回一个*完整*的 JSON 对象?

DELPHI:泛型和多态性

java - Java中如何知道Observer类发送的泛型对象?

c# - 如何解决错误 : "The command [...] exited with code 1"?

c# - 如何给 ListBox 项目上色?

c# - 单词搜索益智游戏

java - 在接口(interface)中使用 Java 泛型来强制实现以实现类型作为参数的方法

java - 类型安全、Java 泛型和查询

Java - 使用 WatchEvent 抑制未经检查的转换警告是否安全?

C# - 如何使用具有一个属性的接口(interface)在类之间进行通信