es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

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)?

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para resolver el error, puedes cambiar el tipo de retorno del método FromJson a Notification<object>?, lo cual te permite retornar tanto un Notification<object> como null.

    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();
    }
    

    Esto te permite retornar un UserUpdateProfileNotification, que hereda de Notification<userupdateprofilenotificationpayload>, como un Notification<object>.

    Alternativamente, puedes usar una conversión explícita para convertir UserUpdateProfileNotification a Notification<object>, de la siguiente manera:

    if (notification is UserUpdateProfileNotification)
    {
        var userNotification = (UserUpdateProfileNotification)notification;
        // la notificación ahora está convertida a UserUpdateProfileNotification
        // por lo que puedo acceder a la propiedad notification.Payload.AccountId
    }
    

    Esto te permite acceder a la propiedad AccountId del objeto Payload dentro de UserUpdateProfileNotification. 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 retorno Notification<object>? para el método FromJson es una solución más limpia en este caso.

Comments are closed.