How can I add a type constraint to include anything serializable in a generic method?

前端 未结 4 1636
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 09:45

My generic method needs to serialize the object passed to it, however just insisting that it implements ISerializable doesn\'t seem to work. For example, I have a struct ret

4条回答
  •  -上瘾入骨i
    2021-01-01 10:42

    You can't do this totally via generic constraints, but you can do a couple things to help:

    1) Put the new() constraint on the generic type (to enable the ability to deserialize and to ensure the XmlSerializer doesn't complain about a lack of default ctor):

    where T : new()
    

    2) On the first line of your method handling the serialization (or constructor or anywhere else you don't have to repeat it over and over), you can perform this check:

    if( !typeof(T).IsSerializable && !(typeof(ISerializable).IsAssignableFrom(typeof(T)) ) )
        throw new InvalidOperationException("A serializable Type is required");
    

    Of course, there's still the possibility of runtime exceptions when trying to serialize a type, but this will cover the most obvious issues.

提交回复
热议问题