我有一个库,程序中的逻辑有一个问题。如果您可以帮助我-我会说:“谢谢”。非常感谢。 代码:
public class Report
{
/// <summary>
/// An empty constructor, just instantiates the object.
/// </summary>
public Report()
{
}
/// <summary>
/// A method that receives a message from another object,
/// and prints it out to the Console.
/// </summary>
/// <param name="message">The message to be printed.</param>
public void ReceiveMessage(String message)
{
Console.WriteLine(message);
}
}
private Report reportObject;
public void EnterThinkingState() {
Thread.Sleep(rng.Next(1000) + 1);
Status = "thinking";
reportObject.ReceiveMessage(Name + " is " + Status);
Thread.Sleep(rng.Next(1000) + 1);
}
问题是:我的班级-是一个图书馆。我该如何创建一种自适应方法(Receive),用户可以使用该方法在任意位置(记录器,控制台,文件等)输出信息。 我应该使用虚拟方法吗?还是创建一个界面?或者如何将其与事件绑定?如果我们谈论典型情况,我知道如何使用事件。 感谢您的帮助。 再一次,对不起我的英语不好。
答案 0 :(得分:0)
您可以使用其他方法来实现此目的。 以下代码显示了如何定义和使用接口:
public interface IReceiverBase
{
void ReceiveMessage(string message);
}
public class Report
{
private readonly IReceiverBase _iReceiverBase;
public Report(IReceiverBase iReceiverBase)
{
_iReceiverBase = iReceiverBase;
}
public void DoSomething()
{
// Do something here
_iReceiverBase.ReceiveMessage("Something done ...");
}
}
public class ConsoleMessageReceiver : IReceiverBase
{
public void ReceiveMessage(string message)
{
Console.WriteLine(message);
}
}
public class DebugMessageReceiver : IReceiverBase
{
public void ReceiveMessage(string message)
{
Debug.WriteLine(message);
}
}
class Program
{
static void Main(string[] args)
{
var repConsole = new Report(new ConsoleMessageReceiver());
repConsole.DoSomething();
var repDebug = new Report(new DebugMessageReceiver());
repDebug.DoSomething();
Console.Read();
}
}