//in SomeClass
pprivate Client _client = new Client();
public Dictionary<string, Channel> Channels = new Dictionary<string, Channel>();
public SomeClass()
{
Channels.Add("main", _client.GetChannel("#channelName"));
Channels.Add("secundary", _client.GetChannel("#secondChannelName"));
}
//in Client
public Channel GetChannel(string channelName)
{ //return a channel specific to this Client.
}
当我创建SomeClass()
时,字典会从当前Channel
返回中填充_client.GetChannel()
个对象。它将Channel
保存到词典中,但我希望它将-method-添加到词典中;并且每次调用字典都会返回当前_client.GetChannel()
在其被调用的那一刻返回的内容。
例如,当调用Channels["main"]
时,我希望它为我调用Client.GetChannel("#channelName")
并返回它返回的任何内容。
我怎样才能做到这一点?
答案 0 :(得分:0)
将频道名称存储在字典中:
//in SomeClass
public Client Client = new Client();
public Dictionary<string, string> Channels = new Dictionary<string, string>();
public SomeClass()
{
Channels.Add("main", "#channelName");
Channels.Add("secundary", "#secondChannelName");
}
//in Client
public Channel GetChannel(string channelName)
{ //return a channel specific to this Client.
}
然后,为了获取Channel对象,请调用GetChannel:
string channelName;
Channels.tryGetValue("main", out channelName);
Channel thisChannel = Client.GetChannel(channelName);
如果您从SomeClass外部执行此操作(因为客户端是私有的),您可以从SomeClass公开一个公共方法来执行相同的操作:
// to run it in a different class:
Channel thisChannel = someClassInstance.GetChannelObject("#main");
// in SomeClass:
public Channel GetChannelObject(string channelID) {
string channelName;
Channels.tryGetValue(channelID, out channelName);
Channel thisChannel = Client.GetChannel(channelName);
return(thisChannel);
}
答案 1 :(得分:0)
你可以这样做:
public Dictionary<string, Func<Channel>> Channels
= new Dictionary<string, Func<Channel>>();
public SomeClass()
{
Channels.Add("main", () => _client.GetChannel("#channelName"));
Channels.Add("secundary", () => _client.GetChannel("#secondChannelName"));
}
然后你可以这样称呼它:
var main = Channels["main"]();
或者:
var main = Channels["main"].Invoke();