原帖地址:一种简单,轻量,灵活的C#对象转Json对象的方案
在原方案中缺少了对可空值类型的处理
protected void AppendObject(object obj) { if (obj == null) Buff.Append("null"); else if (obj is String) AppendString((String)obj); else if (obj is ValueType) AppendValueType(obj);//值类型 else if (_LoopObject.ContainsKey(obj) == false) { _LoopObject.Add(obj, null); if (obj is IDictionary) AppendJson((IDictionary)obj); else if (obj is IEnumerable) AppendArray((IEnumerable)obj); else if (obj is DataSet) AppendDataSet((DataSet)obj); else if (obj is DataTable) AppendDataTable((DataTable)obj); else if (obj is DataView) AppendDataView((DataView)obj); else AppendOther(obj); _LoopObject.Remove(obj); } else { Buff.Append("undefined"); } } private static System.Reflection.Module SystemModule = typeof(int).Module; private void AppendValueType(object obj) { var type = obj.GetType(); if (obj.GetType().Module == SystemModule)//如果是系统模块中的值类型对象 { if (obj is Int32) AppendInt32((Int32)obj); else if (obj is Boolean) AppendBoolean((Boolean)obj); else if (obj is DateTime) AppendDateTime((DateTime)obj); else if (obj is Double) AppendDouble((Double)obj); else if (obj is Enum) AppendEnum((Enum)obj); else if (obj is Decimal) AppendDecimal((Decimal)obj); else if (obj is Char) AppendChar((Char)obj); else if (obj is Single) AppendSingle((Single)obj); else if (obj is Guid) AppendGuid((Guid)obj); else if (obj is Byte) AppendByte((Byte)obj); else if (obj is Int16) AppendInt16((Int16)obj); else if (obj is Int64) AppendInt64((Int64)obj); else if (obj is SByte) AppendSByte((SByte)obj); else if (obj is UInt32) AppendUInt32((UInt32)obj); else if (obj is UInt64) AppendUInt64((UInt64)obj); else if (Nullable.GetUnderlyingType(type) != null)//判断是否是可空值类型 { if (obj is Int32?) AppendInt32(((Int32?)obj).Value); else if (obj is Boolean?) AppendBoolean(((Boolean?)obj).Value); else if (obj is DateTime?) AppendDateTime(((DateTime?)obj).Value); else if (obj is Double?) AppendDouble(((Double?)obj).Value); else if (obj is Decimal?) AppendDecimal(((Decimal?)obj).Value); else if (obj is Char?) AppendChar(((Char?)obj).Value); else if (obj is Single?) AppendSingle(((Single?)obj).Value); else if (obj is Guid?) AppendGuid(((Guid?)obj).Value); else if (obj is Byte?) AppendByte(((Byte?)obj).Value); else if (obj is Int16?) AppendInt16(((Int16?)obj).Value); else if (obj is Int64?) AppendInt64(((Int64?)obj).Value); else if (obj is SByte?) AppendSByte(((SByte?)obj).Value); else if (obj is UInt32?) AppendUInt32(((UInt32?)obj).Value); else if (obj is UInt64?) AppendUInt64(((UInt64?)obj).Value); } } else if (_LoopObject.ContainsKey(obj) == false) { _LoopObject.Add(obj, null); AppendOther(obj); _LoopObject.Remove(obj); } else { Buff.Append("undefined"); } }
现在可以处理可空值类型了,性能还能有一点点的提升 呵呵