一个C#泛型的问题请教

Bind 2010-10-21 11:34:54
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;
}

类似这个,这个方法应该怎么写?
...全文
215 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
Bind 2010-10-22
  • 打赏
  • 举报
回复
我还是停留在面向对象的编程框框里,总想用多态来解决问题
Bind 2010-10-22
  • 打赏
  • 举报
回复
你太牛XX了,我爱你
Bind 2010-10-22
  • 打赏
  • 举报
回复
刚好看到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>();
xuld 2010-10-21
  • 打赏
  • 举报
回复
先定义一个类: NewClientBase<TChannel> : ClientBase<TChannel>

new NewClientBase<TChannel>() .ClientCredentials
njw1028 2010-10-21
  • 打赏
  • 举报
回复
顶到前面去,有高人
soar_net 2010-10-21
  • 打赏
  • 举报
回复
可以的吗?违反WCF契约规则了吧
bloodish 2010-10-21
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 bind 的回复:]
bloodish

晕,这些类是系统生成的,肯定不能加接口或改动的

要是能直接改类,我直接在类里加上username和pwd就得了
[/Quote]

明白你的意思了,你直接没将清楚哦

public static class AuthClass
{
public static void Foo<T>(ClientBase<T> client) where T : class
{
client.ClientCredentials.Account = "admin";
client.ClientCredentials.Password = "pwd";
}
}
Bind 2010-10-21
  • 打赏
  • 举报
回复
bloodish

晕,这些类是系统生成的,肯定不能加接口或改动的

要是能直接改类,我直接在类里加上username和pwd就得了
bloodish 2010-10-21
  • 打赏
  • 举报
回复
自己再抽象出一个接口,具体见代码


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() }
}
}
Bind 2010-10-21
  • 打赏
  • 举报
回复
大家没理解我的意义

我的实际案例是这样的,我的客户端跟服务端之间用自定义用户名和密码的形式进行权限验证

这样的话,如果我有一百个接口契约,我就会有一百个在客户端的代理类,这些代理类是vs在引用服务时生成的,都是从ClientBase<TChannel>继承而来

而我每次用这些代理类去调用服务的时候,都得进行
instance.ClientCredentials.UserName.Username="oo";
instance.clientCredentials.UserName.password="xx";
比较烦人

不知大家可有好的解决方案,我就想写个静态方法,把每个代理类传进去,这个方法自动帮我设置好用户名和密码。
可是ClientCredentials不是某个接口的成员,也不某个公共基类的成员,所以在写这个静态方法的时候,我就没法进行多态了

对泛型不了解,不知有没有相应的方法,请大家多多指教。
zjx198934 2010-10-21
  • 打赏
  • 举报
回复
先实例化类!就可以访问此对象了

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧