I\'m trying to design an application that will allow the user to specify an Enum type in an XML, and from that the application will execute a specific method tied to that enum (
When I try to serialize your class with XmlSerializer
, the innermost exception I get is:
Message="System.Enum is an unsupported type. Please use [XmlIgnore] attribute to exclude members of this type from serialization graph."
This is self-explanatory: you cannot serialize a member whose type is the abstract type System.Enum.
You can, however, serialize a member of type System.Object
provided that all possible types of value that might be encountered are declared statically by using [XmlInclude(typeof(T))]. Thus you can modify your type as follows:
// Include all possible types of Enum that might be serialized
[XmlInclude(typeof(Enummies.BigMethods))]
[XmlInclude(typeof(Enummies.SmallMethods))]
public class TESTCLASS
{
private Enum _MethodType;
// Surrogate object property for MethodObject required by XmlSerializer
[XmlElement(Order = 1, ElementName = "MethodType")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object MethodTypeObject
{
get { return MethodType; }
set { MethodType = (Enum)value; }
}
// Ignore the Enum member that cannot be serialized directly
[XmlIgnore]
public Enum MethodType
{
get { return _MethodType; }
set { _MethodType = value; }
}
public TESTCLASS() { }
public TESTCLASS(Enummies.BigMethods bigM)
{
MethodType = bigM;
}
public TESTCLASS(Enummies.SmallMethods smallM)
{
MethodType = smallM;
}
}
And XML will be generated as follows:
BIG_THREE
Or
SMALL_TWO
Notice the xsi:type
attribute? That is a W3C standard attribute that an element may use to explicitly assert its type. Microsoft uses this attribute to represent type information for polymorphic elements as explained here.
Sample fiddle.
You might want to check that the value type is a known Enum
type in the setter for MethodObject
(rather than the getter) but this is not required for XML serialization.