简体   繁体   中英

C# Generics Extension Method Issues

so I'm fairly new to writing generic transform model extensions and I was trying to go from a model to an azure service bus message which works as expected. But I'm now trying to do the reverse where it can go from a message to a specified type.

The extension method currently looks like so.

    public static class ModelExtensions
    {
        public static Message ToMessage<TModel>(this TModel model) =>
            new Message(
                Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(model)));

        public static TType FromMessage<TModel, TType>(this TModel model)
        {
            return JsonConvert.DeserializeObject<TType>(JsonConvert.SerializeObject(model));
        }
    }

Is there a way to do the reverse of what I have just done to many types depending what is specified on the other side of the extension method for example if on the outside I have done something like.

message.FromMessage()

Any help would be appreciated, Thanks in advance, Chris.

Should be as simple as

public static TModel FromMessage<TModel>(this Message message)
  => JsonConvert.DeserializeObject<TModel>(Encoding.UTF8.GetString(message.Body));

Usage

var result = message.FromMessage<MyLovelyHorse>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM