我试图制作一个程序来编译一段用我正在制作的 BASIC 变体编写的代码。
我试图找出问题所在,但我做不到。我将"String.StartsWith(("更改为String =="something"并且它起作用了,但我需要在这一部分中使用StartsWith。
private String ComprobarCmd(String txt)
{
String texto = txt;
if (texto.StartsWith("CLS")) return "1";
if (texto.StartsWith("SETCURSOR")) return "2";
if (texto.StartsWith("PRINT")) return "3";
if (texto.StartsWith("END")) return "1000";
return "F";
}
我希望它返回一个字符串,但它只是给了我这个错误(它是西班牙语(:
************** Texto de la excepción **************
System.NullReferenceException: Referencia a objeto no establecida como instancia de un objeto.
en JBasic_Compiler.Form1.ComprobarCmd(String txt) en D:ProgramasProyectos VBJBasic CompilerJBasic CompilerJBasic CompilerForm1.cs:línea 67
en JBasic_Compiler.Form1.Compilar(String path) en D:ProgramasProyectos VBJBasic CompilerJBasic CompilerJBasic CompilerForm1.cs:línea 54
en JBasic_Compiler.Form1.Form1_Load(Object sender, EventArgs e) en D:ProgramasProyectos VBJBasic CompilerJBasic CompilerJBasic CompilerForm1.cs:línea 28
en System.Windows.Forms.Form.OnLoad(EventArgs e)
en System.Windows.Forms.Form.OnCreateControl()
en System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
en System.Windows.Forms.Control.CreateControl()
en System.Windows.Forms.Control.WmShowWindow(Message& m)
en System.Windows.Forms.Control.WndProc(Message& m)
en System.Windows.Forms.ScrollableControl.WndProc(Message& m)
en System.Windows.Forms.Form.WmShowWindow(Message& m)
en System.Windows.Forms.Form.WndProc(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
en System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
当 txt 为空时,您需要处理大小写。在方法开头添加: if (txt == null) return "text to return if txt is null";
仅此而已。
另外,请阅读有关空值和对象的更多信息。
双 eqaulity 符号有效,因为您可以将静态字符串与 null 进行比较。但是startsWith 是字符串对象上的方法,您需要实例化此对象才能调用它。