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

258
Views
¿Cómo verificar si los parámetros son nulos cuando se usan constructores de registros posicionales y/o propiedades de inicio?

Me gustaría verificar que no se asignen parámetros nulos a los campos de registro y permitir que las propiedades tengan comentarios. Descubrí que el siguiente arreglo es el truco para los comentarios, pero me faltan ideas para verificar los parámetros nulos sin convertir este registro en una clase.

Entonces, una pregunta: ¿Es posible verificar durante el tiempo de ejecución que no se asignarán valores nulos a los campos de registro? Si es así, ¿cómo podría uno hacerlo mientras todavía usa registros?

 public record Test(string TestString) { /// <summary> /// This is one way to get a comment on record properties. Are there others? /// </summary> public string TestString { get; init; } = TestString; }

El código también es esencial aquí .

Esta es una adición, pero tal vez ayude con la respuesta aceptada y el comentario de un código diferente.

Fue porque el código en esencia hizo una verificación nula como

 public record Test(string TestString) { /// <summary> /// This is one way to get a comment on record properties. Are there others? /// </summary> public string TestString { get; init; } = TestString ?? throw new ArgumentNullException(); }

Por una razón u otra, no incluí esta reflexión en la pregunta original si tal vez haya un camino más corto. :)

<editar: La ArgumentNullException.ThrowIfNull(obj) de .NET 6 podría ser útil aquí (o ThrowHelper).

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Tiene que manejar cheques durante la asignación en línea, como ya descubrió en su esencia.

Una posibilidad es llamar a un método de extensión para envolver cualquier comportamiento.

 public record Test(string TestString) { /// <summary> /// This is one way to get a comment on record properties. Are there others? /// </summary> public string TestString { get; init; } = ValidationExtensions.Validate(TestString); } public static class ValidationExtensions { public static string Validate(string input) { if (string.IsNullOrEmpty(input)) throw new NullReferenceException(); return input; } }

Esto arrojará correctamente durante la inicialización del registro:

 var x = new Test(null);
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!