namespace ClassLibrary1 { class InnerClass//私类 { public string Test(string s) { return "" + DateTime.Now + " " + s; } public void Test2(string s) { Debug.Print(s); } private string Test3(string s)//私方法 { return "private " + DateTime.Now + " " + s ; } } } 反射: [TestMethod] public void Test2() { var assembly = Assembly.Load("ClassLibrary1"); var obj = assembly.CreateInstance("ClassLibrary1.InnerClass"); var m=obj.GetType().InvokeMember("Test",BindingFlags.InvokeMethod ,null,obj, new object [] { "123"}); Debug.Print(""+m); //BindingFlags类型枚举,BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod 组合才能获取到private私有方法 var k = obj.GetType().InvokeMember("Test3", BindingFlags.NonPublic | BindingFlags.Instance |BindingFlags.InvokeMethod, null, obj, new object[] { "123" }); Debug.Print("" + k); }
如果类只有一个带参数的构造函数,如:
public InnerClass(string s) {
Text = s;
}
那反射时候这样:
var obj = assembly.CreateInstance("ClassLibrary1.InnerClass",true,BindingFlags.CreateInstance,null,new string[] {"123" }, new System.Globalization.CultureInfo("en-US"), new object[] { });