我对C#还很陌生,我从下面的行中得到了一个NullReferenceException:
CommandEntered(readedLine);
其余的相关代码应该是这样的:
using System;
namespace Eksamensprojekt
{
class StregSystemCLI : IStregSystemUI
{
IStregSystem stregSystem = new StregSystem();
public event StregSystemEvent CommandEntered;
public StregSystemCLI(IStregSystem stregSystem)
{
this.stregSystem = stregSystem;
}
public void Start()
{
Console.WriteLine(stregSystem.activeProducts().ToString());
Console.WriteLine("Enter your username and then a product ID and hit enter to buy a product. Example: 'username 49340'");
Console.WriteLine("Alternatively, to buy multiple instances of the same product you can use: 'username amount ID' instead. Example: 'username 10 49340'");
string readedLine = Console.ReadLine();
Console.WriteLine("{0}", readedLine);
if(readedLine != null)
{
CommandEntered(readedLine);
}
}
}
}
namespace Eksamensprojekt
{
class StregSystemCommandParser
{
IStregSystem stregSystem;
IStregSystemUI stregSystemUI;
public StregSystemCommandParser(IStregSystem stregSystem, IStregSystemUI stregSystemUI)
{
stregSystem = new StregSystem( );
stregSystemUI = new StregSystemCLI(stregSystem);
stregSystemUI.CommandEntered += ParseCommand;
}
void ParseCommand(string command)
{
...lots of code here, that I don't think is relevant to the solution
}
}
}
namespace Eksamensprojekt {
public class Program
{
static void Main(string[] args)
{
IStregSystem stregSystem = new StregSystem();
IStregSystemUI ui = new StregSystemCLI(stregSystem);
StregSystemCommandParser sc = new StregSystemCommandParser(stregSystem, ui);
ui.Start();
}
}
}
namespace Eksamensprojekt
{
public delegate void StregSystemEvent(string Command);
}
我希望以上内容在没有完整代码的情况下可读。我希望发生的是,如果在readedLine中输入了一些内容,并且字符串不是null,我希望它触发一个事件,导致方法ParseCommand()在类StregSystemCommandParser中运行。如何制作修复NullReferenceException的解决方案?
没有侦听器连接到CommandEntered
事件。
调用事件的正确C#习惯用法是:
CommandEntered?.Invoke(readedLine);