C#动态创建类实例并动态调用指定的函数

类定义:

namespace DynamicFuncTest
{
    class TestClass03
    {
        private string sText = "Member string";

        public string TestFunction01()
        {
            return "TestClass03 TestFunction01";
        }

        public string TestFunction02(string sStr)
        {
	    sText = sStr;
            return "TestClass03 TestFunction02" + sText;
        }
    }
}

调用:

        private void Btn_Exectue_ClassBuildInFunc_Click(object sender, EventArgs e)
        {
            if (T_FunctionInClass.Text.Length == 0)
            {
                MessageBox.Show("Pls choice function.");
                return;
            }

            Type type = System.Type.GetType("DynamicFuncTest.TestClass03");
            MethodInfo mi = type.GetMethod(T_FunctionInClass.Text);
            object testClass = Activator.CreateInstance(type);
            //TestClass03 testClass = new TestClass03();                // It is ok too.
            
            /*
             * // Can use below steps to load the dll, then get the type.
             * Assembly assemblyTmp = Assembly.LoadFrom(sFileName);
             * Type type = assemblyTmp.GetType("NameSpace.ClassName");
             * object testClass = assemblyTmp.CreateInstance(type);
             */

            //object[] objParams = null;
            //T_Result_ClassBuildIn.Text = (string)mi.Invoke(testClass, objParams);

            object[] objParams = new object[1];
            objParams[0] = T_Params_InClass.Text;
            T_Result_ClassBuildIn.Text = (string)mi.Invoke(testClass, objParams);
        }

如果类在dll中,则先加载dll。




你可能感兴趣的:(.Net)