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

怎甘沉沦 提交于 2019-11-30 10:43:19

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.

I wrote a length blog article on this subject that you may find helpful. It mainly goes into binary serialization but the concepts are applicable to most any serialization format.

The long and short of it is

  • There is no way to add a reliable generic constraint
  • The only way to check and see if an object was serializable is to serialize it and see if the operation succeeds

The only way to know if an object is serializable is to try to serialize it.

In fact, you were asking how to tell if a type "is serializable", but the actual question will be with respect to objects. Some instances of a type may not be serializable even if the type is marked [Serializable]. For instance, what if the instance contains circular references?

Instead of

XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

try

XmlSerializer xmlSerializer = new XmlSerializer(message.GetType());

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!