反射调用静态方法
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ConApp
{
class Program
{
static void Main(string[] args)
{
// 使用TryParse,出现异常时,赋值为最小值
string str = "4x";
DateTime dt = DateTime.MaxValue;
DateTime.TryParse(str, out dt);
// 使用TryParse,出现异常时,赋值为最小值
int i = 2;
int.TryParse(str, out i);
// 调用静态方法
Type t = typeof(Sys);
object obj = t.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, new object[] { 2 });
// 调用一般方法
Type type = typeof(Sys);
Object objT = type.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
int ii = (int)type.InvokeMember("GetInt", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, objT, new object[] { 1 });
Console.ReadKey();
}
}
public class Sys
{
public static string GetName(int id)
{
return string.Format("Your name is : test_{0}", id + 1);
}
public int GetInt(int value)
{
return value + 100;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ConApp
{
class Program
{
static void Main(string[] args)
{
// 使用TryParse,出现异常时,赋值为最小值
string str = "4x";
DateTime dt = DateTime.MaxValue;
DateTime.TryParse(str, out dt);
// 使用TryParse,出现异常时,赋值为最小值
int i = 2;
int.TryParse(str, out i);
// 调用静态方法
Type t = typeof(Sys);
object obj = t.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, new object[] { 2 });
// 调用一般方法
Type type = typeof(Sys);
Object objT = type.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
int ii = (int)type.InvokeMember("GetInt", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, objT, new object[] { 1 });
Console.ReadKey();
}
}
public class Sys
{
public static string GetName(int id)
{
return string.Format("Your name is : test_{0}", id + 1);
}
public int GetInt(int value)
{
return value + 100;
}
}
}