ex-22-07

来自「Programming Csharp Source Code(代码) Prog」· 代码 · 共 61 行

TXT
61
字号
// Example 22-07: Late binding of COM objects

private void btnAdd_Click(
   object sender, System.EventArgs e)
{
   Invoke("Add");
}

private void btnSubtract_Click(
   object sender, System.EventArgs e)
{
   Invoke("Subtract");
}

private void btnMultiply_Click(
   object sender, System.EventArgs e)
{
   Invoke("Multiply");
}

private void btnDivide_Click(
   object sender, System.EventArgs e)
{
   Invoke("Divide");
}


private void Invoke(string whichMethod)
{
   Double left, right, result;
   left = Double.Parse(textBox1.Text);
   right = Double.Parse(textBox2.Text);

   // create a Type object to hold type information
   Type comCalcType;

   // an array for the arguments
   object[] inputArguments = 
      {left, right };

   // get the type info from the COM object
   comCalcType = 
      Type.GetTypeFromProgID(
         "ComCalculator.ComCalc");

   // create an instance
   object comCalcObject = 
      Activator.CreateInstance(comCalcType);

   // invoke the method dynamically and 
   // cast the result to double
   result = (Double) comCalcType.InvokeMember(
      whichMethod,                // the method to invoke
      BindingFlags.InvokeMethod,  // how to bind
      null,                       // binder
      comCalcObject,              // the COM object
      inputArguments);            // the method arguments

   label1.Text = result.ToString();
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?