I have two child classes that inherit from BaseClass. I am attempting to use reflection on an object of type BaseClass to get the XmlRootAttribute.ElementName value. So if someone passed in a BaseClass object, how could I get the value "ChildClass1" or "ChildClass2"?

[Serializable]
public class BaseClass {
   // Base properties
}

[XmlRoot("ChildClass1")]
public class ChildClass1 : BaseClass {
   // Child1 properties
}

[XmlRoot("ChildClass2")]
public class ChildClass2 : BaseClass {
   // Child2 properties
}
有帮助吗?

解决方案

Here is the solution I came up with:

public static string GetElementName(BaseClass target)
{
    XmlRootAttribute attribute = target.GetType().GetCustomAttribute<XmlRootAttribute>();
    return attribute == null ? null : attribute.ElementName;
}

And the usage looks like this:

BaseClass baseClass = new BaseClass();
BaseClass child1 = new ChildClass1();
BaseClass child2 = new ChildClass2();

Console.WriteLine(GetElementName(baseClass)); // empty string
Console.WriteLine(GetElementName(child1)); // ChildClass1
Console.WriteLine(GetElementName(child2)); // ChildClass2
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top