获取应用于此实例的 c# 属性?

Get c# attribute applied to this instance?

是否可以从 class 中检索应用于 class 实例的属性值?这方面的一个例子是:

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 对此进行了测试。不知道反射有没有变化