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 (using a dictionary). I'm getting hung up on the Enum portion of the XML.
public class TESTCLASS
{
private Enum _MethodType;
[XmlElement(Order = 1, ElementName = "MethodType")]
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;
}
}
public class Enummies
{
public enum BigMethods { BIG_ONE, BIG_TWO, BIG_THREE }
public enum SmallMethods { SMALL_ONE, SMALL_TWO, SMALL_THREE }
}
And then trying to serialize the TESTCLASS results in an exception:
string p = "C:\testclass.xml";
TESTCLASS testclass = new TESTCLASS(Enummies.BigMethods.BIG_ONE);
TestSerializer<TESTCLASS>.Serialize(p, testclass);
System.InvalidOperationException: The type Enummies+BigMethods may not be used in this context.
My serialization method looks like this:
public class TestSerializer<T> where T: class
{
public static void Serialize(string path, T type)
{
var serializer = new XmlSerializer(type.GetType());
using (var writer = new FileStream(path, FileMode.Create))
{
serializer.Serialize(writer, type);
}
}
public static T Deserialize(string path)
{
T type;
var serializer = new XmlSerializer(typeof(T));
using (var reader = XmlReader.Create(path))
{
type = serializer.Deserialize(reader) as T;
}
return type;
}
}
I tried including some checking/casting in the MethodType Getter, but this results in the same error.
public Enum MethodType
{
get
{
if (_MethodType is Enummies.BigMethods) return (Enummies.BigMethods)_MethodType;
if (_MethodType is Enummies.SmallMethods) return (Enummies.SmallMethods)_MethodType;
throw new Exception("UNKNOWN ENUMMIES TYPE");
}
set { _MethodType = value; }
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…