Calling a generic reflection

class GenClass<T>
{
public void Note(T t)
{
Console.WriteLine(t);
}
}
调用

the Assembly.Load ASS = var ( "TextCord");
// call to the generic reflector
var type_q = ass.GetType ( "TextCord.GenClass`1");
var = typeMake type_q.MakeGenericType (new new the Type [] {typeof (String) });
var = genclass the Activator.CreateInstance (typeMake);
var = typeMake.GetMethod Note ( "Note", the Type new new [] {typeof (String)});
note.Invoke (genclass, new new Object [] { "3333" });
there are several important parts

We get this time back with some generic character "` 1 ', then this is what does that mean? In fact, this is our time to compile the code into il, a placeholder for something similar system specified, a general argument is "` 1 ", TClass <T, U> two is the" `2."

The second is to pay attention to the place, we initialize this T when you need to call it MakeGenericType (http://www.amjmh.com/v/BIBRGZ_558768/) method, used to initialize the type T, just as we, like new

// As such
var genClass = new GenClass <string> ();
the third major is that we call the dynamic method, we generally CreateInstance is created when the reflecting object instance, or by a strong turn invoke methods using the dynamic type, here we are in a dynamic fashion calls, the following example

//反射调用泛型
var type_q = ass.GetType("TextCord.GenClass`1");
var typeMake = type_q.MakeGenericType(new Type[] { typeof(string) });
var genclass = Activator.CreateInstance(typeMake);
var note = typeMake.GetMethod("Note",new Type[] { typeof(string)});
note.Invoke(genclass, new object[] { "3333"});
//强转
GenClass<string> y = (GenClass<string>)Activator.CreateInstance(typeMake);
y.Note("yyyyy");
//动态类型
dynamic d = Activator.CreateInstance(typeMake);

 

Guess you like

Origin www.cnblogs.com/hyhy904/p/11498526.html