问题描述
我对委托和泛型方法有点困惑.
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?
即:
//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
作为泛型类型参数关闭.
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.
在您编写的示例代码中
someDelegate = GenericMethod;
但是 someDelegate
应该有什么类型?它必须要么明显关闭(GenericDelegate
),要么用来自外部作用域的泛型类型参数关闭:
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.
这篇关于分配给委托的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论