是否可以从该类的内部检索应用于该类的实例的属性的值?例如:

class Host {
    [XmlElement("NAME")]
    public ChildClass c { get; set; }
}

[Serializable()]
class ChildClass : IXmlSerializable {
    ...
    void IXmlSerializable.WriteXml(XmlWriter writer) {
        OtherClass desiredElement = ...
        string desiredElementName = ???
        XmlSerializer = new XmlSerializer(desiredElement.GetType(), new XmlRootAttribute(desiredElementName));
        serializer.Serialize(writer, desiredElment);
    }
}


desiredElementName应该包含NAME的位置?

最佳答案

这不能直接完成,您必须将父级的引用传递给子级。如果这不是问题,则可以:

public class Host {
    public Host()
    {
        c = new ChildClass(this);
    }

    [XmlElement("NAME")]
    public ChildClass c { get; set; }
}

[Serializable()]
public class ChildClass : IXmlSerializable {
    private object _parent { get; }

    public ChildClass(object parent)
    {
        _parent = parent;
    }

    public void IXmlSerializable.WriteXml(XmlWriter writer) {

        var props = _parent.GetType().GetProperties();
        var propElement = props.Where(p => p.PropertyType == GetType()).FirstOrDefault();
        var desiredElementName = propElement.CustomAttributes.FirstOrDefault(p => p.AttributeType == typeof(XmlElementAttribute))?.ConstructorArguments.FirstOrDefault()?.Value;

        var desiredElement = _parent;

        XmlSerializer = new XmlSerializer(desiredElement.GetType(), new XmlRootAttribute(desiredElementName));
        serializer.Serialize(writer, desiredElment);
    }
}


尽管我不确定desiredElement是否包含您所想到的对象。

请注意:我使用.net core 2.0进行了测试。我不知道反射是否有变化。

关于c# - 获取适用于此实例的C#属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48212534/

10-12 01:25