C# 如何将类对象转换为字符串?
我有一个通过web服务(WCF)提供的类对象。该类具有String类型的属性和一些自定义类类型 如何获取自定义类类型的属性的属性名和属性名 我尝试使用getProperties()进行反射,但失败了。GetFields()使我获得了一些成功。如果属性类型为string类型,我还希望获取自定义类型属性的属性 这是我的密码C# 如何将类对象转换为字符串?,c#,.net,wcf,reflection,C#,.net,Wcf,Reflection,我有一个通过web服务(WCF)提供的类对象。该类具有String类型的属性和一些自定义类类型 如何获取自定义类类型的属性的属性名和属性名 我尝试使用getProperties()进行反射,但失败了。GetFields()使我获得了一些成功。如果属性类型为string类型,我还希望获取自定义类型属性的属性 这是我的密码 public static string ToClassString(this object value) { if (value == null) re
public static string ToClassString(this object value)
{
if (value == null)
return null;
var builder = new StringBuilder();
builder.Append(value.GetType().Name + "{ ");
foreach (var prop in value.GetType().GetFields(
BindingFlags.Public
| BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.GetProperty))
{
builder.Append("{ ");
builder.Append(prop.Name + " , ");
switch (prop.FieldType.Namespace)
{
case "System":
builder.Append(prop.GetValue(value) + " }");
break;
default:
builder.Append(prop.GetValue(value).ToClassString() + " }");
break;
}
}
builder.Append("}");
return builder.ToString();
}
我得到的输出是
NotifyClass{{UniqueId,16175}{NodeInfo,NodeInfo{}}{EventType,
SAPDELETE}
下面是我要将其实例转换为字符串的类
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="NotifyReq", WrapperNamespace="wrapper:namespace", IsWrapped=true)]
public partial class Notify
{
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="custom:namespace", Order=0)]
public int UniqueId;
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="custom:namespace", Order=1)]
public eDMRMService.NodeInfo NodeInfo;
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="custom:namespace", Order=2)]
public string EventType;
public Notify()
{
}
public Notify(int UniqueId, eDMRMService.NodeInfo NodeInfo, string EventType)
{
this.UniqueId = UniqueId;
this.NodeInfo = NodeInfo;
this.EventType = EventType;
}
}
不需要重新发明轮子。使用 仅此而已 您还可以使用JavaScriptSerializer
string s = new JavaScriptSerializer().Serialize(yourObject);
输出与您期望的有什么不同?问题是它不包括
NodeInfo
的成员吗?如果是这样:NotInfo
看起来像什么?成员是公共的吗?它是公共类型吗?etcI不想使用外部程序集JavaScriptSerializer不是外部程序集。@印度程序员JavaScriptSerializer
是内置的(System.Web.Script.Serialization
)请注意,您需要添加对System.Web.Extensions
的引用,以便能够使用具有JavaScriptSerializer
类的System.Web.Script.Serialization
。
string s = new JavaScriptSerializer().Serialize(yourObject);