开发者

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.GetTy开发者_开发百科pe());

            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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜