开发者

How to identify types with the serialization attribute?

I need to define a method parameter that should ideally only accept object arguments that have been decorated with the Serializable attribute. The method task is to persist 开发者_高级运维the object argument into a XML document.

I understand I can eventually check for SerializationException, but i'd rather be able to neatly define this as a part of the method contract. So, is there any way I can isolate types that have been decorated with this attribute?


One option is to use the IsSerializable property of the Type class:

public void Serialize(object obj)
{
    if (obj.GetType().IsSerializable)
    {
        // do work
    }
}


You can use the GetCustomAttributes function on the type of the object.

    public void Serialize(object itemToSerialize)
    {
        var hasAttribute = itemToSerialize.GetType().GetCustomAttributes(typeof(SerializableAttribute), true).Any();

        // Do stuff.
    }

However, don't forget that normal serialization supports ISerializable too. So therefore, the IsSerializable property on the type is probably more appropriate.

Edit I think you are after a manner to have the compiler enforce the parameter have the attribute. There is no way to do this. You would have to use a runtime check as above and throw an exception.

Generics would typically be your friend for this type of task, and in this case, you could use a generic parameter where the type implements ISerializable, but as you are aware that would exclude cases where serialization is declared rather than implemented.


If you could further restrict things so that only objects that implement ISerializable are allowed then you could use generics to get compile-time checking

public void Serialize<T>(T obj) where T : ISerializable
{
    // Do work
}

Unfortunately this doesn't count as an answer to your question because not every Serializable class implements ISerializable

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜