111,092
社区成员




class Program
{
static void Main(string[] args)
{
Test test = new Test();
Console.WriteLine(test.Method<int>("AAA")); //111
Console.WriteLine(test.Method<string>("AAA")); //哈哈哈AAA
Console.WriteLine(test.Method<double>("AAA")); //3.1415
Console.WriteLine("-----------------------");
//反射泛型调用
Type type0 = Type.GetType("System.Int32");
Type type1 = Type.GetType("System.String");
Type type2 = Type.GetType("System.Double");
MethodInfo baseMethod = typeof(Test).GetMethod("Method").GetGenericMethodDefinition();
object value0 = baseMethod.MakeGenericMethod(type0).Invoke(test, new[] { "AAA" });
object value1 = baseMethod.MakeGenericMethod(type1).Invoke(test, new[] { "AAA" });
object value2 = baseMethod.MakeGenericMethod(type2).Invoke(test, new[] { "AAA" });
Console.WriteLine(value0); //111
Console.WriteLine(value1); //哈哈哈AAA
Console.WriteLine(value2); //3.1415
}
}
public class Test
{
public T Method<T>(string sql)
{
if (typeof(T) == typeof(int)) return (T)((object)111);
if (typeof(T) == typeof(string)) return (T)((object)("哈哈哈" + sql));
if (typeof(T) == typeof(double)) return (T)((object)3.1415);
return default(T);
}
}