Tengo algunos campos que no aceptan valores NULL que quiero inicializar dentro de métodos auxiliares, llamados desde un constructor, para reducir el desorden dentro del constructor:
private FlowLayoutPanel _flowPanel; private ComboBox _printersComboBox; //... public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings) { InitializeComponent(); PostInitializeComponent(); // this is where _flowPanel etc get initialized // ... } ¿Cómo evito advertencias como Non-nullable field '_flowPanel' must contain a non-null value when exiting constructor. Consider declaring the field as nullable ¿ Non-nullable field '_flowPanel' must contain a non-null value when exiting constructor. Consider declaring the field as nullable ?
La mejor idea que se me ha ocurrido hasta ahora:
public static void Assert([DoesNotReturnIf(false)] bool condition) { if (!condition) throw new InvalidOperationException(); } public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings) { InitializeComponent(); PostInitializeComponent(); Assert(_flowPanel != null); Assert(_printersComboBox != null); //... }Todavía se está complicando cuando hay muchos campos. ¿Hay algo mejor que esto?
Es un proyecto de .NET 6, así que podría usar lo último y lo mejor.
¿Qué hay de definirlos como anulables como:
FlowLayoutPanel? _flowPanel;
¿Podría hacer que PostInitializeComponent devuelva el FlowPanel?
luego
public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings) { InitializeComponent(); _flowPanel = PostInitializeComponent(); // ... }Si PostInitializeComponent hace un montón de trabajo, tal vez extraiga la parte que construye FlowPanel y haga que la devuelva y la asigne.
Tienes pocas opciones:
[MemberNotNull] en los métodos auxiliares. Esto es un poco detallado pero debería funcionar. Consulte https://stackoverflow.com/a/64958374/2855742 .Otra opción es declarar los campos como:
private FlowLayoutPanel _flowPanel = null!; private ComboBox _printersComboBox = null!; Esto obliga al compilador a considerar estos campos como inicializados y el ! suprime las advertencias de que el valor es nulo pero el campo no es anulable.
Tenga en cuenta que agregar la asignación nula no cambia el código generado. No hay impacto en el tiempo de ejecución, solo en el tiempo de diseño.