gpt4 book ai didi

具有接口(interface)混淆的 C# 通用 ClientBase

转载 作者:行者123 更新时间:2023-11-30 15:59:50 30 4
gpt4 key购买 nike

ClientBase 的 C# 定义是:

public abstract class ClientBase<TChannel> : ICommunicationObject, 
IDisposable
where TChannel : class

这清楚地表明了 TChannel 类型上的 class 约束。据我所知,这意味着您不能在声明您自己的类时使用泛型的接口(interface)类型。因此,给定这样声明的服务:

public IMyService
...
public MyService : IMyService
...

这应该有效:

public MyServiceClient : ClientBase<MyService> 

这应该:

public MyServiceClient : ClientBase<IMyService> 

但显然我不理解,因为该示例显示了以下声明:

public partial class SampleServiceClient : 
System.ServiceModel.ClientBase<ISampleService>, ISampleService

更重要的是,我正在尝试抽象身份验证,并使用实用程序方法正确关闭客户端:

    public TResult WithClient<TInterface, T, TResult>(T service, 
Func<TInterface, TResult> callback)
where T : ClientBase<TInterface>, TInterface
{
service.ClientCredentials.UserName.UserName = userName;
service.ClientCredentials.UserName.Password = password;

try
{
var result = callback(service);
service.Close();
return result;
}
catch (Exception unknown)
{
service.Abort();
throw unknown;
}
}

但这给了我编译器错误:

The type 'TInterface' must be a reference type in order to use it as parameter 'TChannel' in the generic type or method 'ClientBase<TChannel>'

有人可以消除这里的困惑吗?我做错了什么?

----更新----

根据@InBetween,解决方案是将 where TInterface : class 约束添加到我的实用程序方法中:

    public TResult WithClient<TInterface, T, TResult>(T service, 
Func<TInterface, TResult> callback)
where TInterface : class
where T : ClientBase<TInterface>, TInterface
{
service.ClientCredentials.UserName.UserName = userName;
service.ClientCredentials.UserName.Password = password;

try
{
var result = callback(service);
service.Close();
return result;
}
catch (Exception unknown)
{
service.Abort();
throw unknown;
}
}

最佳答案

class constraint 将泛型类型约束为引用类型。根据定义,接口(interface)是引用类型。你不能做的是使用值类型作为通用类型:ClientBase<int>将是一个编译时错误。

至于第二个错误,你没有约束TInterface然后在 ClientBase<TInterface> 中使用它.因为ClientBase将其泛型类型约束为引用类型( class ),您需要约束 TInterface相应地。

关于具有接口(interface)混淆的 C# 通用 ClientBase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949583/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com