简体   繁体   English

C# 委托与通用方法一起使用以返回任务<T>

[英]C# Delegate use with Generic Method to return Task<T>

I' m missing something here.我在这里遗漏了一些东西。 I 'll be as clear as I can be.我会尽可能清楚。

let's say I have this method :假设我有这个方法:

    public Task<CustomClass> TestMethod(string one, string two, int three)
        {
            throw new NotImplementedException();
        }

and I want to create a generic method that takes methods like these (through a delegate) and does something.我想创建一个通用方法,它采用这些方法(通过委托)并做一些事情。

so let's say that I have this class with a delegate and a generic method:所以假设我有一个带有委托和通用方法的类:

public static class SomeClass
{
    public delegate T CallbackMethodDelegate<T>(params object[] args);
    public static void InvokeMethod<T>(CallbackMethodDelegate<Task<T>> method, params object[] args) where T: class
        {
            method.Invoke(args);
        }

}

my understanding says that T can be a class, so I should be able to do this somewhere in the code :我的理解是 T 可以是一个类,所以我应该能够在代码的某个地方做到这一点:

    SomeClass.InvokeMethod<CustomClass>(TestMethod, "one", "two", 3);

But I get compile error但我得到编译错误

CS1503:Argument 1: cannot convert from 'method group' to 'SomeClass.CallBackMethodDelegate<Task<CustomClass>>'

I thought it might be an async thing but even if I change the delegate to void I get the same error.我认为这可能是一个异步的事情,但即使我将委托更改为 void 我也会得到同样的错误。 Any ideas what I'm missing?有什么我想念的想法吗? Seems like I'm misunderstanding something important about delegates or generics here.似乎我在这里误解了关于委托或泛型的重要内容。 Thank you all in advance.谢谢大家。

as the error suggests your method is not compatible with the delegate.因为错误表明您的方法与委托不兼容。 The delegate requires object[] as a parameter your method has 3 explicit parameters string,string,int this is not compatible.委托需要object[]作为参数,您的方法有 3 个显式参数string,string,int这是不兼容的。

what you can do if you really need this is you can create a set of invoke methods that cover wide range of methods:如果你真的需要,你可以做的是创建一组涵盖各种方法的调用方法:

void InvokeMethod<TResult>(Func<Task<TResult>> method, TParam1 param1)
void InvokeMethod<TParam1, TResult>(Func<TParam1,Task<TResult>> method, TParam1 param1)
void InvokeMethod<TParam1,TParam2, TResult>(Func<TParam1, TParam2 ,Task<TResult>> method, TParam1 param1, TParam2 param2)

and so on as many parameters you need to have.等等,你需要有多少参数。

you can reduce those methods to single implementation that is not type safe but not accessible directly您可以将这些方法简化为非类型安全但无法直接访问的单个实现

void InvokeMethodImpl(Delegate method, params object[] args)
   => method.DynamicInvoke(args);

so all generic methods would just call this method:所以所有泛型方法都会调用这个方法:

 void InvokeMethod<TParam1, TResult>(Func<TParam1,Task<TResult>> method, TParam1 param1) 
      => InvokeMethodImpl(method, param1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM