public abstract class ClientBase<TChannel> : ICommunicationObject, IDisposable where TChannel : class
{
    ...    public ClientCredentials ClientCredentials { get; }
    ...
}
这是wcf客户端代理的抽象泛型基类我现在有很多个派生出来的代理类,我能不能通过一个静态方法来访问这个ClientCredentials属性like:
static void foo(ClientBase<T> client)
{
    client.ClientCredentials.OOXX;
}类似这个,这个方法应该怎么写?

解决方案 »

  1.   

    可以的吗?违反WCF契约规则了吧
      

  2.   

    先定义一个类:  NewClientBase<TChannel> : ClientBase<TChannel> new NewClientBase<TChannel>() .ClientCredentials
      

  3.   

    大家没理解我的意义我的实际案例是这样的,我的客户端跟服务端之间用自定义用户名和密码的形式进行权限验证这样的话,如果我有一百个接口契约,我就会有一百个在客户端的代理类,这些代理类是vs在引用服务时生成的,都是从ClientBase<TChannel>继承而来而我每次用这些代理类去调用服务的时候,都得进行
    instance.ClientCredentials.UserName.Username="oo";
    instance.clientCredentials.UserName.password="xx";
    比较烦人不知大家可有好的解决方案,我就想写个静态方法,把每个代理类传进去,这个方法自动帮我设置好用户名和密码。
    可是ClientCredentials不是某个接口的成员,也不某个公共基类的成员,所以在写这个静态方法的时候,我就没法进行多态了对泛型不了解,不知有没有相应的方法,请大家多多指教。
      

  4.   

    自己再抽象出一个接口,具体见代码
            public interface IClientCredentialsAuth
            {
                ClientCredentials ClientCredentials { get; }
            }        public class ClientCredentials
            {
                public string Account { get; set; }
                public string Password { get; set; }
            }        public abstract class ClientBase<T> : IDisposable, ICommunicationObject, IClientCredentialsAuth where T : class
            {
                public static void Auth(IClientCredentialsAuth auth, string acc, string pwd)
                {
                    auth.ClientCredentials.Account = acc;
                    auth.ClientCredentials.Password = pwd;
                }            public ClientCredentials ClientCredentials
                {
                    get { return new ClientCredentials() }
                }
            }
      

  5.   

    bloodish晕,这些类是系统生成的,肯定不能加接口或改动的要是能直接改类,我直接在类里加上username和pwd就得了
      

  6.   


    明白你的意思了,你直接没将清楚哦public static class AuthClass
            {
                public static void Foo<T>(ClientBase<T> client) where T : class
                {
                    client.ClientCredentials.Account = "admin";
                    client.ClientCredentials.Password = "pwd";
                }
            }
      

  7.   

    刚好看到c#新特性扩展方法public static class AuthClass
            {
                public static void Foo<T>(this ClientBase<T> client) where T : class
                {
                    client.ClientCredentials.Account = "admin";
                    client.ClientCredentials.Password = "pwd";
                }
            }加上this后就可以直接在服务代理类上调用了clientproxy.Foo<ClientProxyType>();