25

我有一个通过 Web 服务 (WCF) 提供的类对象。该类具有字符串类型的属性和一些自定义类类型。

如何获取自定义类类型的属性的属性名称和属性名称。

我尝试使用 GetProperies() 进行反射,但失败了。如果属性类型是字符串类型,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();
}

我得到的输出为

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;
    }
}        
4

1 回答 1

84

无需重新发明轮子。使用Json.Net

string s = JsonConvert.SerializeObject(yourObject);

就这些。

您还可以使用 JavaScriptSerializer

string s = new JavaScriptSerializer().Serialize(yourObject);
于 2013-04-17T13:02:20.863 回答