开发者

Is there a standard simple string deserialization interface/pattern for .NET?

I could easily w开发者_JAVA技巧rite one, but I'm wondering if there is already a standard string deserialization interface or pattern somewhere in the framework that creates/populates an object based on a string.

Basically I'm looking to do the opposite of ToString(). Every object supports ToString(), which is handy, but it would be nice if I could go the other way, and actually (re)create an object from that string. Obviously this isn't possible for all objects, but that's fine.

I looked at ISerializable but it's silly complicated (having SerializationInfos and StreamingContexts and all sorts of nonsense) for something that should be a core feature, imo. I'm envisioning something like this:

public interface IDeserializable {
    void Deserialize( string data );
}

Upon further thought, it would be nice (and be more symmetric to ToString) if I could actually pass the string to a constructor, but I wouldn't be able to use an interface to represent this. I'd have to use reflection on the type and check for a constructor that accepts a single string, and use reflection to instantiate it.


As a reflection/Type- friendly alternative to TryParse:

var conv = TypeDescriptor.GetConverter(type);
object value = conv.ConvertFromInvariantString(s);


Many types support the TryParse method. http://social.msdn.microsoft.com/Search/en-us?query=tryparse


Yes. Thanks to Reflection, its possible to serialize/deserialize almost any object.

http://msdn.microsoft.com/en-us/library/7ay27kt9(v=VS.100).aspx

Also ToString IS NOT SERIALIZATION. Its only simplified textual representation. In most cases it only returns name of the type.

Edit: Well XML is string. And you can use binary serialization and save it using Base64 encoding. Question is if you want it to remain human-readable while serialized.


You want to use the DataContract serializer or NewtonSoft Json/Bson serializers.


No, there's no built in way of doing this. ToString() can't be expected to produce something that has enough information to deserialize from, because that's not it's intended purpose. The default version of Object.ToString() actually gives you nothing that could be used to deserialize something. It'd only work on classes that specifically implement ToString() this way, in which case it'd make more sense to have an Interface with some other method and not rely on ToString() (SerializeString() or something).

The closest thing is the XML Serializer, or the DataContractSerializer that was already mentioned.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜