代码之家  ›  专栏  ›  技术社区  ›  Ryall

XML序列化不会写出属性

  •  1
  • Ryall  · 技术社区  · 17 年前

    previous question ,我很难将懒惰的人结合起来<T>我的XML序列化建议使用的泛型。

    public struct Lazy<T> where T : class, new()
    {
        private T _Value;
    
        public bool HasValue
        {
            get
            {
                return (_Value != null);
            }
        }
    
        public T Value
        {
            get
            {
                if (!HasValue)
                    _Value = new T();
    
                return _Value;
            }
        }
    }
    

    MSDN Docs 假设在一个属性上有一个[XmlElement(“ElementName”)]是可以的,而且它确实能够很好地反序列化。当我序列化一个对象时,问题就出现了。我正在运行以下代码:

    class SomeClass
    {
        [XmlElement("ExternalElementName")]
        public ComplexElementType InternalElementName
        { 
            get { return _InternalElementName.Value; } 
        }
    
        protected Lazy<ComplexElementType> _InternalElementName;
    }
    

    SomeClass someClass = new SomeClass();
    someClass.InternalElementName.ComplexElementTypeChild = "some string";
    
    // serialize...
    

    奇怪的是,这在调试器中运行良好,但XML中没有输出任何元素。不懒惰<T>元素运行良好。有什么想法吗?

    3 回复  |  直到 9 年前
        1
  •  3
  •   Guffa    17 年前

    问题是该属性没有setter。即使可以获取值来序列化它,也无法对其进行反序列化,因为无法将值放回新对象中。

        2
  •  1
  •   John Saunders    17 年前

        3
  •  0
  •   Aistina    17 年前

    不确定问题出在哪里(我总是发现XML序列化程序的行为很不稳定),但是为什么不使用 Nullable<T> 上课?不要重新发明轮子:)