MirlvsMaximvs
MirlvsMaximvs

Reputation: 1483

namespace name 'p' could not be found (are you missing a using directive or an assembly reference?)

I'm working in a generic method in order to deserialize an xml document depends on the contain. It tries to deserialize all posible cases.

Here my code snippet:

 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;
 }

But the compiler says the type or namespace name p could not be found. Do I miss a using directive or an assembly reference? What went wrong?

Upvotes: 1

Views: 590

Answers (1)

Lee
Lee

Reputation: 144136

p is a variable containing a reference to a Type instance, but you are trying to use it as a type parameter.

To do what you want, you'll need to invoke the method using reflection:

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

Upvotes: 5

Related Questions