後期綁定的幾種方法

來源:互聯網
上載者:User

 

一、使用System.Activator類

System.Activator提供了兩個靜態方法:createinstance()和createinstancefrom(),如果包含類的程式集未出現在Appdomain中,調用:createinstance()和createinstancefrom()會導致該程式集被載入。

using System;

using System.Reflection;

 

namespace ConsoleApplication5

{

    classProgram

    {

        staticvoidMain(string[] args)

        {

            Assemblyassembly = Assembly.Load("Foo.dll");

            Typetype = assembly.GetType("NMFoo.Calc");

            objectobj = Activator.CreateInstance(type);

        }

    }

}

二、  使用System.Appdomain。與之前的Activator.CreateInstance類似,不過通過他們可以選擇將對象建立在哪個Appdomain中,此外“AndUnwarp()”版本會返回一個對對象的直接引用。

using System;

using System.Reflection;

class Program {

   staticvoidMain() {

      objectobj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(

                                  "Foo.dll", "NMFoo.Calc");

 

   }

}

三、使用System.Reflecton.ConstructorInfo類,該類的invoke()方法在內部為建構函式建立了一個後期綁定,並通過這個綁定調用建構函式

using System;

using System.Reflection;

 

namespace ConsoleApplication5

{

    classProgram

    {

        staticvoidMain(string[] args)

        {

            Assemblyassembly = Assembly.LoadFrom(@"C:\Foo.dll");

            Typetype = assembly.GetType("NMFoo.Calc");

            ConstructorInfoconstructorInfo = type.GetConstructor(new Type[0]);

            objectobj = constructorInfo.Invoke(new object[0]);

        }

    }

}

 

四、  使用System.Type類

通過System.Type類的非靜態方法Invokemember()可以建立一個在編譯期間未知的類的執行個體,只需要在調用的時候使用BIndingFlages枚舉量中的CreateInstance即可

using System;

using System.Reflection;

 

namespace ConsoleApplication5

{

    classProgram

    {

        staticvoidMain(string[] args)

        {

            Assemblyassembly = Assembly.LoadFrom(@"C:\Foo.dll");

            Typetype = assembly.GetType("NMFoo.Calc");

            Objectobj = type.InvokeMember(

              null, // Don't need toprovide a name for calling a constructor.

              BindingFlags.CreateInstance,

              null, // Don't need abinder.

              null, // Don't need atarget object since we build it.

              new Object[0]); // No parameters.

            //Here, 'obj' is a reference toward an instance of NMFoo.Calc.

        }

    }

}

五、對於數組和委派物件的執行個體

  為建立一個數組,必須調用System.Array類中的靜態方法Createinstance()

 為建立一個委派物件,必須調用System.Delegate類中的CreateDelegate()方法

 

六、一次綁定,多次調用

 

using System;

using System.Reflection;

 

namespace ConsoleApplication5

{

    classProgram

    {

        staticvoidMain()

        {

            objectobj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(

                                       "Foo.dll", "NMFoo.Calc");

            Typetype = obj.GetType();

            //Create a late bind with the 'sum'?method.

            MethodInfomethodInfo = type.GetMethod("Sum");

            object[]parameters = new object[2];

            parameters[0] = 7;

            parameters[1] = 8;

            intresult;

            //10 calls to 'Sums'

            //for (int i = 0;i < 10; i++)

                result = (int)methodInfo.Invoke(obj, parameters);

                Console.WriteLine(Convert.ToString(result));

 

        }

    }

}

 

七、利用介面:使用後期綁定的正確方法

1、 建立包含介面的程式集的代碼(InterfaceAsm.CS)

using System;

using System.Collections.Generic;

using System.Text;

 

namespace NMFoo

{

    publicinterface ICalc

    {

        intSum(int a, intb);

    }

}

2、 建立目標類的程式集的代碼(ClassAsm.CS)

using System;

using System.Collections.Generic;

using System.Text;

 

namespace NMFoo

{

    publicclass CalcWithInterface:ICalc

    {

        publicCalcWithInterface()

        {

            Console.WriteLine("Calc.constructor called!");

        }

 

        publicint Sum(int a, int b)

        {

            Console.WriteLine("method Calc.Sum() Called!");

            returna + b;

 

        }

    }

 

}

3、 在編譯期目標類未知的客戶程式集的代碼(ProgramAsm.CS)

using System;

using System.Reflection;

using NMFoo;

using System.IO;

 

namespaceMain

{

    classProgram

    {

        staticvoidMain(string[] args)

        {

            //Console.WriteLine(System.Environment.CurrentDirectory);

            ICalcobj = AppDomain.CurrentDomain.CreateInstanceAndUnwrap("ClassAsm.dll", "NMFoo.CalcWithInterface")as ICalc;

            //intresult = obj.Sum(7, 8);

            Console.WriteLine(System.Environment.CurrentDirectory);

        }

    }

}

4、

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.