Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
Campos no anulables inicializados dentro de un método llamado desde el constructor

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.

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

¿Qué hay de definirlos como anulables como:

FlowLayoutPanel? _flowPanel;

over 4 years ago · Santiago Trujillo Report

0

¿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.

over 4 years ago · Santiago Trujillo Report

0

Tienes pocas opciones:

  1. Use [MemberNotNull] en los métodos auxiliares. Esto es un poco detallado pero debería funcionar. Consulte https://stackoverflow.com/a/64958374/2855742 .
  2. Devuelve valores de tus métodos auxiliares (¿quizás tuplas?) y deconstruye y asigna directamente en los campos que deseas inicializar.
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!