[英]How to check if an object is null
这是我的代码:
public static class SerializationUtil
{
public static string Serialize(object obj)
{
if (obj == null)
return string.Empty;
StringWriter writer = new StringWriter();
new System.Web.UI.LosFormatter().Serialize(writer, obj);
return writer.ToString();
}
public static object Deserialize(string data)
{
if (data == null)
return null;
return (new System.Web.UI.LosFormatter()).Deserialize(data);
}
}
我遇到的问题是:当obj为null时,我调用serialize方法时会引发错误。 所以我想检查obj值是否为null。 我放置的代码现在无法正常工作,因为在检查obj值时,它永远不会为空。
解决:
在答案中查看我的帖子
好,我知道了。 我查看了异常的详细信息,它期望对象类可序列化。 我使类可序列化,并且可以正常工作
using System;
[Serializable] //the missing piece
public class RegisterFormData
{
public string username { get; set; }
public string pass1 { get; set; }
public string pass2 { get; set; }
public string email { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
}
我真的不认为您所描述的是可能的。 如果仅在上面几行中检查obj
是否不为null,则它也不为null。 如果您收到NullReferenceException
,则可能是由于Serialize
方法本身中的其他内容为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.