我正在使用泛型方法来反序列化xml文档取决于包含.它试图反序化所有可能的案件.
这是我的代码片段:
private static Dictionary<Type, byte> getMessageDictionary() {
Dictionary<Type, byte> typesIO = new Dictionary<Type, byte>();
typesIO.Add(typeof (Type1), 1);
typesIO.Add(typeof (Type2), 11);
typesIO.Add(typeof (Type3), 12);
return typesIO;
}
public static object GetContainer(XmlDocument xd) {
foreach(KeyValuePair<Type, byte> item in getMessageDictionary()) {
try {
Type p = item.Key;
var z = Utils.XmlDeserialize<p> (xd.OuterXml);
return z;
} catch {
continue;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
但编译器说p无法找到类型或命名空间名称.我是否会错过using指令或汇编参考?什么地方出了错?
p是包含对Type实例的引用的变量,但您尝试将其用作类型参数.
要做你想做的事,你需要使用反射来调用方法:
Type p = item.Key;
var method = typeof(Utils).GetMethod("XmlDeserialize").MakeGenericMethod(p);
var z = (XmlDocument)method.Invoke(null, new object[] { xd.OuterXml });
Run Code Online (Sandbox Code Playgroud)