【问题标题】:Creating Generic Delegates with Generic Interface Arguments使用通用接口参数创建通用委托
【发布时间】:2013-10-29 12:32:17
【问题描述】:

我想创建一个通用委托。它将委托具有泛型类型作为参数的函数。

例如: 我有一个界面:

public interface IProblemState<T> : IComparable<IProblemState<T>>, IEquatable<IProblemState<T>>
        where T : IEquatable<T>
{}

我有两个不同的班级

public class Class1 : IEquatable<Class1>
{ }

public class Class2 : **IProblemState<Class1>**
{ }

在我有了代表之后

public delegate SortedSet<IProblemState<T>> ExpanderDelegate<T>(IProblemState<T> currentState) 
        where T : IEquatable<T>;

我无法使用具有派生类参数(类 2 的实例)的函数创建委托。

例如:

SortedSet<**Class2**> expander(**Class2** currentState)
{}

ExpanderDelegate<Class2> expanderDel = new ExpanderDelegate(**expander**);

当我想创建委托时,出现以下错误。

“expander”没有重载匹配委托“ExpanderDelegate”

我想将此委托与所有具有派生参数的函数一起使用。

C# 可以吗?

谢谢。

【问题讨论】:

  • 哇,课程太复杂了,请您把问题简化一下。我认为您的问题与 C# 中的协变和逆变有关

标签: c# generics interface delegates


【解决方案1】:

当然不能。代表说:给我一个可以将 any IProblemState&lt;T&gt; 作为参数的函数,然后给它一个 可以采用 Class2 的函数。

如果有一个Class3 也实现了IProblemState&lt;T&gt; 怎么办?当然,委托签名说我应该能够将Class3 的实例作为参数传递。但是该函数不允许它(它只允许Class2 实例)。这就是为什么不能将该函数分配给该委托类型的变量的原因。

你可以做的是使用这个通用委托:

public delegate SortedSet<T> ExpanderDelegate<T,U>(T currentState) 
    where T : IProblemState<U> where U: IEquatable<U>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多