简体   繁体   English

C# - XML将复杂类序列化为其原始类型

[英]C# - XML serialize a complex class as only its primitive type

Is it possible to take a complex class "A", which represents a primitive type with added information - such as valid values for that primitive , include an instance of "A" in "B", and XML serialize "B" with "A" appearing only as its primitive type? 是否可以采用复杂的类“A”,它表示具有附加信息的基本类型 - 例如该基元的有效值,包括“B”中的“A”实例,以及“A”的XML序列化“B” “只是作为原始类型出现?

Class A<T> {
  T obj;
  Static  ValidValue<T>[] validValues;
}

Class B {
  A<int> intVal;
  A<string> stringVal;
}

Desired output is just the primitives. 期望的输出只是原始的。 The ValidValues would be used to validate the data after deserialization: ValidValues将用于在反序列化后验证数据:

  <B>
    <A>1</A>
    <A>example</A>
  </B>

Have you tried to use property? 你有没有尝试过使用房产?

public class B {
  private A<int> intVal;
  public int IntVal{
    get{
      return intVal.obj;
    }
    set{
      intVal.obj = value;
    }
  }

  // same for stringval
}

As far as I know xmlserializer will only serialize public properties. 据我所知,xmlserializer只会序列化公共属性。 So it should work. 所以它应该工作。

I may misunderstood your requirement though. 我可能会误解你的要求。

This is easy to do with DataContracts . 使用DataContracts很容易。

You just need to put a [DataContract] attribute on the class, and then decorate only the fields or properties that you want to be serialised with a [DataMember] attribute. 您只需要在类上放置一个[DataContract]属性,然后使用[DataMember]属性修饰要序列化的字段或属性。 You can serialise private fields in this way. 您可以通过这种方式序列化私有字段。

See here for how to serialize such a decorated class . 请参阅此处了解如何序列化这样的装饰类

This is opt-in, ie only the items that you decorate with [DataMember] will be serialised. 这是选择加入,即只有您使用[DataMember]装饰的项目才会被序列化。

For example ( from the MSDN sample here ): 例如( 来自此处的MSDN示例 ):

[DataContract]
public class Person
{
    // This member is serialized.
    [DataMember]
    internal string FullName;

    // This is serialized even though it is private.
    [DataMember]
    private int Age;

    // This is not serialized because the DataMemberAttribute 
    // has not been applied.
    private string MailingAddress;

    // This is not serialized, but the property is.
    private string telephoneNumberValue;

    [DataMember]
    public string TelephoneNumber
    {
        get { return telephoneNumberValue; }
        set { telephoneNumberValue = value; }
    }
}

You could use custom serialization to control what variables are serialized. 您可以使用自定义序列化来控制序列化的变量。 You could then send whatever value you want to the serialized object. 然后,您可以将所需的任何值发送到序列化对象。

See http://msdn.microsoft.com/en-us/library/ty01x675(v=vs.80).aspx 请参阅http://msdn.microsoft.com/en-us/library/ty01x675(v=vs.80).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM