C#通用ClientBase,界面混乱

时间:2016-12-03 15:50:02

标签: c# wcf generics

ClientBase的C#定义是:

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

清楚地表明class类型的TChannel约束。据我所知,这意味着在声明自己的类时不能使用和接口类型。因此,给出了一个如此宣布的服务:

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

这应该有效:

public MyServiceClient : ClientBase<MyService> 

这应该 NOT

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;
        }
    }

1 个答案:

答案 0 :(得分:3)

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

关于第二个错误,您不会限制TInterface,然后在ClientBase<TInterface>中使用它。由于ClientBase将其泛型类型限制为引用类型(class),因此您需要相应地约束TInterface