c# - C# 委托(delegate)可以使用对象类型来更通用吗?

标签 c# functional-programming delegates type-conversion

我想创建一个委托(delegate)和一个可用于调用我的应用程序所需的任意数量的 Web 服务的方法:

例子:

public DateCheckResponseGetDate(DateCheckRequest requestParameters)
{
    delegate object WebMethodToCall(object methodObject);

    WebMethodToCall getTheDate = new WebMethodToCall(WebServices.GetTheDate);

    return (DateCheckResponse)CallWebMethod(getTheDate , requestParameters);
}

public TimeCheckResponse GetTime(TimeCheckRequest requestParameters)
{
    delegate object WebMethodToCall(object methodObject);

    WebMethodToCall getTheTime = new WebMethodToCall(WebServices.GetTheTime);

    return (TimeCheckResponse)CallWebMethod(getTheTime, requestParameters);
}

private object CallWebMethod(WebMethodToCall method, object methodObject)
{
    return method(methodObject);
}

但是,不幸的是,当我尝试编译时,出现了这些错误:

No overload for 'GetTheDate' matches delegate 'WebMethodToCall' No overload for 'GetTheTime' matches delegate 'WebMethodToCall'

看来委托(delegate)应该工作。

WebServices.GetTheDate 和 WebServices.GetTheTime 都采用单个参数(分别为 DateCheckRequest 和 TimeCheckRequest)并且都返回一个值。

那么委托(delegate)不匹配两个网络方法的签名吗? (都接受和返回从对象派生的类型)。

是否可以使用对象类型在 .NET 2.0 中创建一个可重用性很强的委托(delegate)?

最佳答案

我建议您将代码更改为:


public DateCheckResponseGetDate(DateCheckRequest requestParameters)
{
    Func<DateCheckRequest, DateCheckResponse> getTheDate = new Func<DateCheckRequest, DateCheckResponse>(WebServices.GetTheDate);

    return CallWebMethod(getTheDate , requestParameters);
}

//DEFINE CallWebMethod ADEQUATELY!
public T CallWebMethod<T,U> (Func<T,U> webMethod, U arg)
{
    return webMethod(arg);
}

这样你就可以避免所有丑陋的向下转换:)

关于c# - C# 委托(delegate)可以使用对象类型来更通用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/734698/

相关文章:

java - 正在打印可选[值]

c# - List<T> 中 T 是匿名委托(delegate)的可能吗?

c# - OpacityMask 无法按预期在 C# 代码中工作

c# - 在vs2012中设置为起始页

c# - 基于运行时输入的依赖注入(inject)

java - 函数式编程 : How to carry on the context for a chain of validation rules

scala - 什么是 "functional way"以避免将状态选择上下文向下传递到调用堆栈?

c# - 是什么导致了 MSSQL 中的错误 "Operation on non-blocking socket would block"?

c# - 我可以只举办没有委托(delegate)的事件吗?

android - kotlin 委托(delegate)属性,在 get() 方法中我如何访问该值?