Upcasting a “tipo padre” en las factorías en C#.
Este es el código que me gustaría escribir al final:
var notification = NotificationFactory.FromJson(jsonString);
if (notification is UserUpdateProfileNotification)
{
// notification es de tipo UserUpdateProfileNotification, así que puedo acceder a notification.Payload.AccoundId
}
Esto es lo que he intentado hasta ahora:
public abstract class Notification<t>
{
public string Type { get; set; }
public T Payload { get; set; }
}
public class UserUpdateProfileNotificationPayload
{
public Guid AccountId { get; set; }
}
public class UserUpdateProfileNotification: Notification<userupdateprofilenotificationpayload>
{
public UserUpdateProfileNotification(UserUpdateProfileNotificationPayload payload)
{
Type = "USER_UPDATE_PROFILE";
Payload = payload;
}
}
public static class NotificationFactory
{
public static Notification<object> FromJson(string notification)
{
var parsedNotif = JsonSerializer.Deserialize<><object>>(notification);
if (parsedNotif.Type == "USER_UPDATE_PROFILE")
{
var concreteType = JsonSerializer.Deserialize<userupdateprofilenotification>(notification);
return new UserUpdateProfileNotification(concreteType.Payload);
}
throw new NotImplementedException();
}
}
El error que obtuve:
No se puede convertir implícitamente el tipo ‘UserUpdateProfileNotification’ a ‘Notification
Para mí, convertir Notification<x>
a Notification<object>
con x heredando de object debería ser “automático”. Pero no lo es. ¿Cuál es la mejor manera de expresar esta idea en C# (10)?
davy.ai
Para resolver el error, puedes cambiar el tipo de retorno del método
FromJson
aNotification<object>?
, lo cual te permite retornar tanto unNotification<object>
comonull
.Esto te permite retornar un
UserUpdateProfileNotification
, que hereda deNotification<userupdateprofilenotificationpayload>
, como unNotification<object>
.Alternativamente, puedes usar una conversión explícita para convertir
UserUpdateProfileNotification
aNotification<object>
, de la siguiente manera:Esto te permite acceder a la propiedad
AccountId
del objetoPayload
dentro deUserUpdateProfileNotification
. Sin embargo, esto puede no ser ideal si tienes muchos tipos diferentes de notificaciones, ya que requeriría muchas conversiones explícitas. Usar el tipo de retornoNotification<object>?
para el métodoFromJson
es una solución más limpia en este caso.