简体   繁体   English

如何在C#中检查字符串是否包含可反序列化的数据?

[英]How to check if a String contains Deserializable data in C#?

我们将在为特定列进行序列化之后保存数据,因此在检索数据时以及在反序列化之前如何检查字符串是否可反序列化?

Ensuring that a string represents a valid serialized object is nearly as hard as performing deserialization itself, because you would need to walk the serialized object graph, figuring out where each serialized field starts, and what would be the data that goes into that field. 确保字符串代表有效的序列化对象几乎与执行反序列化本身一样困难,因为您将需要遍历序列化的对象图,弄清楚每个序列化字段从何处开始以及进入该字段的数据是什么。

The only operations that you could save are the allocations of the object and its dependents. 您可以保存的唯一操作是对象及其依赖项的分配。 These operations are certainly not free, but they are highly optimized, so your savings are not going to be overly significant. 这些操作当然不是免费的,但是它们是高度优化的,因此您的节省不会过高。

Instead of pre-validating the string before deserialization, you could take a speculative approach, and assume that your deserialization will succeed. 您可以采用一种推测性的方法,而不是在反序列化之前预先验证字符串,并假设您的反序列化将成功。 Your code could jump right into deserializing your string, and in most cases it will succeed! 您的代码可能会跳入反序列化字符串的过程,在大多数情况下,它将成功! * To ensure that your code does not break when the string is invalid, wrap deserialization calls into a try/catch , and watch for deserialization exceptions. *为确保在字符串无效时代码不会中断,请将反序列化调用包装到try/catch ,并注意反序列化异常。 If you catch any of them, you know that the string was invalid; 如果发现其中任何一个,则说明该字符串无效; if you do not catch deserialization exceptions, you would know that the string is valid, and you would also have your deserialized object ready for use. 如果未捕获反序列化异常,则将知道该字符串有效, 并且还可以使用反序列化的对象。

Assuming XML serialization, your code could do something like this: 假设XML序列化,您的代码可以执行以下操作:

static bool TryDeserialize<T>(string xmlStr, out T obj) {
    var ser = new XmlSerializer(typeof(T));
    using(var stringReader = new StringReader(xmlStr)) {
        using (var xmlReader = new XmlTextReader(stringReader)) {
            try {
                obj = ser.Deserialize(xmlReader);
            } catch {
                obj = default(T);
                return false;
            }
        }
    }
    return true;
}


* If your deserialization fails the overwhelming majority of the time, you may need to re-think this strategy. *如果反序列化在绝大多数情况下都失败了,则可能需要重新考虑该策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM