简体   繁体   中英

How can I constrain T to support DataContractJsonSerializer, and not implement ISerializable everywhere?

I'm working on this extension method and am trying to constrain T so that the method doesn't apply to EVERY object... just the ones that the DataContractJsonSerializer works well with

public static string ToJSONString(this object obj)
    {
        using (var stream = new MemoryStream())
        {
            var ser = new DataContractJsonSerializer(obj.GetType());

            ser.WriteObject(stream, obj);

            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }

The options available inside generics are... Limited. One workaround is to use reflection (typically in a static ctor on a generic type) to check with reflection, but tbh this may be overkill. Could you perhaps add where T : class, new() which may go a long way to limit it to "entity"/DTO types.

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