C# 名称空间名称';p';找不到(是否缺少using指令或程序集引用?)

C# 名称空间名称';p';找不到(是否缺少using指令或程序集引用?),c#,generics,C#,Generics,我正在使用一种通用方法来反序列化xml文档,这取决于包含。它试图反序列化所有可能的案例 下面是我的代码片段: private static Dictionary<Type, byte> getMessageDictionary() { Dictionary<Type, byte> typesIO = new Dictionary<Type, byte>(); typesIO.Add(typeof (Type1), 1); typ

我正在使用一种通用方法来反序列化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;
 }
私有静态字典getMessageDictionary(){
字典类型SIO=新字典();
类型添加(类型(类型1),1);
类型添加(类型2,11);
类型添加(类型3,12);
返回类型SIO;
}
公共静态对象GetContainer(XmlDocument xd){
foreach(getMessageDictionary()中的KeyValuePair项){
试一试{
类型p=项.Key;
var z=Utils.xml反序列化(xd.OuterXml);
返回z;
}抓住{
持续
}
}
返回null;
}

但是编译器说找不到类型或名称空间名称
p
。使用指令或程序集引用时是否遗漏了
?出了什么问题?

p
是一个变量,包含对
类型
实例的引用,但您试图将其用作类型参数

要执行所需操作,需要使用反射调用该方法:

Type p = item.Key;
var method = typeof(Utils).GetMethod("XmlDeserialize").MakeGenericMethod(p);
var z = (XmlDocument)method.Invoke(null, new object[] { xd.OuterXml });

p
是一个变量,包含对
类型
实例的引用,但您试图将其用作类型参数

要执行所需操作,需要使用反射调用该方法:

Type p = item.Key;
var method = typeof(Utils).GetMethod("XmlDeserialize").MakeGenericMethod(p);
var z = (XmlDocument)method.Invoke(null, new object[] { xd.OuterXml });

不能在需要类型的上下文中使用类型为
的对象。泛型类/方法的类型参数必须在编译时已知。不能在预期类型的上下文中使用类型为
type
的对象。泛型类/方法的类型参数必须在编译时已知。我没有任何MakeGenericType(p),我有MakeGenericMethod(),但当我使用它时,它会抛出一个InvalidOperationException,消息绑定操作无法对包含GenericParameters为true的类型或方法执行。。。有什么建议吗?谢谢你reply@Mirlo-是的,你是对的,应该是
MakeGenericMethod
。您要传递给
MakeGenericMethod
p
的类型是什么?如果is包含泛型参数(例如
typeof(IEnumerable)
),则您将得到所描述的异常。在尝试调用
MakeGenericMethod
之前,您需要首先向
p
提供类型参数。好的,最后我使用了类似的方法,但答案非常有用。谢谢。我没有任何MakeGenericType(p),我有MakeGenericMethod()但当我使用它时,它抛出一个InvalidOperationException,消息绑定的操作不能在containsgenericparameters为true的类型或方法上执行。。。有什么建议吗?谢谢你reply@Mirlo-是的,你是对的,应该是
MakeGenericMethod
。您要传递给
MakeGenericMethod
p
的类型是什么?如果is包含泛型参数(例如
typeof(IEnumerable)
),则您将得到所描述的异常。在尝试调用
MakeGenericMethod
之前,您需要首先向
p
提供类型参数。好的,最后我使用了类似的方法,但答案非常有用,谢谢。