答案:尽管将类转为变量然后调用它们会起作用,但在这种情况下,这可能是设计不良的标志。更好的设计会产生副作用,即不需要一开始就不断创建类的新实例。
============
最近我一直(尝试)将 SRP 应用到我的代码中,将所有职责拆分到单独的类中。它工作得很好,代码的可维护性和可重用性提高了很多……但我发现自己一直在做类似 new Table.Type("messages").Get(id);
的事情。
我的大部分类都只包含一个方法。还是。。感觉很尴尬。胆量说这是我不妨将它们全部变成静态类的地步。
所以我想我应该求助于我更有经验的前辈,经常写“new Class().Method()”是不是很常见?或者有更好的处理方法吗?
示例代码:
public void AdminCommands(Channel channel, IrcUser user, string message)
{
var command = message.Split(' ')[0];
switch (command)
{
case "@info":
GetInfo(channel, message);
break;
//----a couple of more commands
}
}
private void GetInfo(Channel channel, string message)
{
Match match = Regex.Match(message, "@info (.+)");
if (match.Success)
{
string search = match.Groups[1].Value;
//Get stored data on the word or sentence, and send the result to chat.
new CommandInfo().Execute(search); //<-------------------- over here.
return;
}
Chat.SendAdminMessage("Message not found.");
}
private void EditMessage(Channel channel, string message)
{
Match match = Regex.Match(message, "@edit (.+?) (.+?) (.+?)=(.+)");
if (match.Success)
{
string type = match.Groups[1].Value;
string id = match.Groups[2].Value;
string toReplace = match.Groups[3].Value;
string replaceWith = match.Groups[4].Value;
//Gets message of 'type' by 'id', and store it back after editing.
new CommandEdit().Execute(type, id, toReplace, replaceWith); //<-here.
}
}
最佳答案
当然可以将CommandEdit和CommandInfo存储为成员变量,然后调用Execute
private CommandInfo mInfo = new CommandInfo();
private void GetInfo(Channel channel, string message)
{
Match match = Regex.Match(message, "@info (.+)");
if (match.Success)
{
string search = match.Groups[1].Value;
//Get stored data on the word or sentence, and send the result to chat.
mInfo.Execute(search); //<-------------------- over here again.
return;
}
Chat.SendAdminMessage("Message not found.");
}
关于c# - 不断地让新的对象正常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22046321/