Kis*_*mar 15 .net c# reflection wcf
我有一个通过Web服务(WCF)来的类对象.该类具有String类型的属性和一些自定义类类型.
如何获取自定义类型的属性的属性名称和属性名称.
我尝试使用GetProperies()进行反射,但失败了.如果Property类型是string类型,GetFields()给了我一些成功,我也想获得自定义类型属性的属性.
这是我的代码.
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();
}
Run Code Online (Sandbox Code Playgroud)
我把输出作为
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;
}
}
Run Code Online (Sandbox Code Playgroud)
I4V*_*I4V 60
无需重新发明轮子.使用Json.Net
string s = JsonConvert.SerializeObject(yourObject);
Run Code Online (Sandbox Code Playgroud)
就这些.
您也可以使用JavaScriptSerializer
string s = new JavaScriptSerializer().Serialize(yourObject);
Run Code Online (Sandbox Code Playgroud)
string jsonString = JsonSerializer.Serialize(yourObject);
Run Code Online (Sandbox Code Playgroud)
这是目前推荐的方式,请在此处System.Text.Json;
阅读更多信息。
归档时间: |
|
查看次数: |
65277 次 |
最近记录: |