使用Reflection时如何解决“未将对象引用设置到对象实例”错误?
Hey Sergio, let's break down why you're getting that "Object reference not set to an instance of an object" error and fix it right away!
The core issue here is that you've declared a Form type variable, but you haven't actually created an instance of the specific theme form you want to show. Using a string with the form's name doesn't automatically connect to the form class—you need to turn that string into a real, instantiated form object.
Option 1: Use Reflection (Flexible for Many Forms)
If you have a lot of theme forms and want to keep your code scalable, reflection lets you dynamically create the form from its name string. Here's how to do it:
// First, get the name of the form you want to launch (e.g., from a ListBox/ComboBox) string selectedFormName = yourListBox.SelectedItem.ToString(); // Get the current assembly where your forms are located var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly(); string fullTypeName = $"{currentAssembly.GetName().Name}.{selectedFormName}"; // Find the form type using its full name Type formType = currentAssembly.GetType(fullTypeName); // Validate we found a valid Form type if (formType != null && typeof(System.Windows.Forms.Form).IsAssignableFrom(formType)) { // Create an instance of the form Form targetForm = (Form)System.Activator.CreateInstance(formType); // Show the form (use ShowDialog() if you want it to be modal) targetForm.Show(); } else { // Handle the case where the form wasn't found System.Windows.Forms.MessageBox.Show($"No se pudo encontrar el formulario: {selectedFormName}"); }
Important Notes for Reflection:
- Case Sensitivity: Make sure the
selectedFormNameexactly matches the form's class name (e.g.,FormVerbosvsformVerboswill fail). - Namespaces: If your forms are in a specific namespace (like
LanguageApp.Themes), include it in thefullTypeName(e.g.,LanguageApp.Themes.FormVerbos).
Option 2: Switch-Case (Safer for Smaller Numbers of Forms)
If you don't have too many theme forms, a switch-case is more straightforward and avoids reflection's overhead. It's also easier to debug:
string selectedFormName = yourListBox.SelectedItem.ToString(); Form targetForm = null; switch (selectedFormName) { case "FormGramatica": targetForm = new FormGramatica(); break; case "FormVocabulario": targetForm = new FormVocabulario(); break; case "FormPronunciacion": targetForm = new FormPronunciacion(); break; // Add cases for all your theme forms default: System.Windows.Forms.MessageBox.Show("Formulario de tema no válido"); break; } // Only show the form if we successfully created it if (targetForm != null) { targetForm.Show(); }
Why You Got the Null Reference Error
Chances are you had code like this before:
// This declares a variable but doesn't assign it to any actual form instance Form myForm; myForm.Show(); // Boom! Null reference error
You need to explicitly create an instance of the specific form class (either via reflection or new FormName()) before calling Show().
内容的提问来源于stack exchange,提问作者Sergio Frías

