这是我想写在最后的代码:
var notification = NotificationFactory.FromJson(jsonString);
if (notification is UserUpdateProfileNotification)
{
// notification is of type UserUpdateProfileNotification so I can access notification.Payload.AccoundId
}
这是我目前所尝试的:
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<Notification<object>>(notification);
if (parsedNotif.Type == "USER_UPDATE_PROFILE")
{
var concreteType = JsonSerializer.Deserialize<UserUpdateProfileNotification>(notification);
return new UserUpdateProfileNotification(concreteType.Payload);
}
throw new NotImplementedException();
}
}
我得到的错误:
不能隐式地将类型UserUpdateProfileNotify转换为Notification
对我来说,转换通知
我得到了一些工作(我使用动态而不是通知和模式匹配工作)
工厂
public class NotificationFactory
{
public static dynamic FromJson(string notification)
{
var parsedNotif = JsonSerializer.Deserialize<Notification<dynamic>>(notification);
if (parsedNotif.Type == "USER_UPDATE_PROFILE")
{
var concreteType = JsonSerializer.Deserialize<UserUpdateProfileNotification>(notification);
return new UserUpdateProfileNotification(concreteType.Payload);
}
throw new NotImplementedException();
}
}
我如何使用:
var notification = NotificationFactory.FromJson(item);
if (notification is UserUpdateProfileNotification notif)
{
log.LogInformation($"{notif.Payload.AccountId}");
}
双重解析不是最优的,但在我的情况下是可以接受的
我发现您的代码有编译错误,但是如果您按照以下方式修改FromJson中的代码,那么它应该可以工作
public static T FromJson<T>(string notification)
{
var parsedNotif = System.Text.Json.JsonSerializer.Deserialize<Notification<object>>(notification);
if (parsedNotif.Type == "USER_UPDATE_PROFILE")
{
var payload = System.Text.Json.JsonSerializer.Deserialize<UserUpdateProfileNotificationPayload>(parsedNotif.Payload.ToString());
object userUpdateProfileNotification = new UserUpdateProfileNotification(payload);
return (T) userUpdateProfileNotification;
}
throw new NotImplementedException();
}