分配给代表的通用方法

分配给代表的通用方法

问题描述:

我对委托和泛型方法感到有些困惑。

I've been a little puzzled with Delegates and Generic Methods.

是否可以将委托分配给具有泛型类型参数的方法?

Is it possible to assign a delegate to a method with a generic type parameter?

IE:

//This doesn't allow me to pass a generic parameter with the delegate.
public delegate void GenericDelegate<T>() 

someDelegate = GenericMethod;
public void GenericMethod<T>() where T : ISomeClass
{

}

我正在尝试将该委托传递给该方法所期望的接口具有通用类型的函数,并具有如下功能:

I'm trying to pass this delegate into the function with a generic type of the interface that the method is expecting, with a function like this:

void CheckDelegate(GenericDelegate<ISomeClass> mechanism);

这样我就可以像这样使用委托:

so that I can use the delegate like so:

someDelegate<ImplementsSomeClass>();


您的问题毫无意义,因为您永远无法使用开放的泛型类型声明存储位置(例如局部变量或字段)。它必须始终处于关闭状态。

Your question makes no sense because you can't ever use an open generic type to declare a storage location (like a local variable or field). It must always be closed.

我了解您想将 GenericDelegate< T> 传递给采用这样的方法一个值作为参数。但是即使这样,委托类型仍以 T 作为通用类型参数关闭。

I understand you want to pass a GenericDelegate<T> to a method taking such a value as an argument. But even then the delegate type becomes closed with T as the generic type parameter.

在示例代码中,您编写了

In your sample code you write

someDelegate = GenericMethod;

但是 someDelegate 应该是什么类型?它必须明显关闭( GenericDelegate< string> )或使用外部作用域的通用类型参数关闭:

but what type is someDelegate supposed to have? It must either be obviously closed (GenericDelegate<string>) or closed with a generic type parameter from the outer scope:

void SomeOuterMethod<T>() where T : ISomeClass {
    GenericDelegate<T> someDelegate = GenericMethod<T>;
}

我希望我理解您的问题。如果没有,请澄清。如果您详细介绍您想完成的任务,我将尝试提出一种实用的解决方案。

I hope I understood your problem. If not, please clarify. If you elaborate a little on what you want to accomplish I'll try to suggest a practical solution.

Haskell等其他语言也有支持用于传递开放通用类型的值(换句话说,您可以使用类型 IEnumerable<> 的变量)。这是实现monad所必需的。 CLR没有该功能。

Other languages like Haskell do have support for passing around values of open generic types (in other words, you can have a variable of type IEnumerable<>). This is required to implement monads. The CLR does not have that feature.

新思路:您可以创建非泛型基本类型来代替委托可以重写的通用方法:

New thought: instead of a delegate you could create a non-generic base type with a generic method that can be overridden:

interface CheckHandler {
 public void Check<T>(T someArg);
}

希望可以解决您的情况。您不能随意传递任何 CheckHandler 。然后可以使用任意类型的参数调用其 Check 方法。

Hope that covers your scenario. You can not freely pass any CheckHandler around. Its Check method can then be called with an arbitrary type argument.