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

173
Views
C# simplificar declaración de cambio

¿Puedo de alguna manera simplificar esta declaración de cambio ya que ambos casos hacen lo mismo solo con otro parámetro de función?

 switch (data.Subscriber.Protocol) { case "email json": builder.Attachments.Add("Očitanje.json", CraftAttachment(data)); break; case "email text": builder.Attachments.Add("Očitanje.txt", CraftAttachment(data)); break; default: break; }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Qué tal algo como esto:

 string attachmentName = data.Subscriber.Protocol switch { "email json" => "Očitanje.json", "email text" => "Očitanje.txt", _ => null }; if (attachmentName is not null) { builder.Attachments.Add(attachmentName, CraftAttachment(data)); }

Cambiar expresión | Referencia de C#

over 4 years ago · Santiago Trujillo Report

0

// Otro enfoque limpio sin usar el caso Swtich:

 var ProtocolAndFileMappings = new Dictionary<string, string>() { {"email json","Očitanje.json"}, {"email text","Očitanje.json"}, {"email png","Očitanje.png"}, {"email Jpeg","Očitanje.Jpeg"} }; builder.Attachments.Add(ProtocolAndFileMappings[data.Subscriber.Protocol], CraftAttachment(data));
over 4 years ago · Santiago Trujillo Report

0

Otro enfoque que utiliza una función local para simplificar la llamada:

 void add(string s) => if (s != null) builder.Attachments.Add(s, CraftAttachment(data)); add( data.Subscriber.Protocol switch { "email json" => "Očitanje.json", "email text" => "Očitanje.txt", _ => null });

(Aunque creo que algunas personas lo criticarían como "demasiado lindo...)

NOTA: Esta solución (al igual que las otras soluciones) tiene un inconveniente.

El código siempre realizará una prueba adicional contra nulo, lo que el cambio directo no hace, por lo que esto es (muy marginalmente) menos eficiente.

Yo personalmente lo haría así (lo que evita el inconveniente):

 void add(string s) => builder.Attachments.Add(s, CraftAttachment(data)); switch (data.Subscriber.Protocol) { case "email json": add("Očitanje.json"); break; case "email text": add("Očitanje.txt") break; default: /* Do nothing */ break; }

Es muy probable que el compilador JIT incorpore funciones locales simples como esa, por lo que no debería haber sobrecarga.

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!