¿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; }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)); }// 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));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.