[英]Get c# attribute applied to this instance?
Is it possible to retrieve the value of an attribute applied to an instance of a class from within that class? 是否可以从该类中检索应用于类实例的属性的值? An example of this would be:
一个例子是:
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);
}
}
Where desiredElementName
should contain NAME
? desiredElementName
应该包含NAME
?
This cannot be done directly, you'll have to pass a reference of the parent to the child. 这不能直接完成,您必须将父项的引用传递给子项。 If this isn't a problem then it is possible:
如果这不是问题,那么有可能:
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);
}
}
Though I'm not sure if desiredElement
contains the object you had in mind. 虽然我不确定
desiredElement
包含你想到的对象。
Please note: I tested this with .net core 2.0. 请注意:我使用.net core 2.0进行了测试。 I don't know if there are changes in reflection.
我不知道反思是否有变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.