【C# 反射】使用 Activator 類 -激活器


創建的實例:

           //需要添加對Education.dll的引用才能正確執行
            object CreateInstanceKind1 = Activator.CreateInstance("Education", "People.Person");

            //不需要添加引用,因為已經傳入路徑參數,它默認在當前程序集的目錄下查找
            object CreateInstanceKind2 = Activator.CreateInstanceFrom("Education.dll", "People.Person");
    
            //需要添加引用,並且引入命名空間
            Type type = typeof(Person);
            object CreateInstanceKind3 = Activator.CreateInstance(type);

 

這在工廠模式中是非常有用的

這樣,可以使程序有更高的擴展性,例如,,下面的例子

如果現在有一個類,專門用來計算交通工具的速度,不同的交通工具計算方法是不一樣的,但是到底有那些交通工具是未知的或者是可變的,這種情況下,我們可能覺得要在添加交通工具的時候,需要修改用來計算速度的那個類,

但如果用Activator .CreateInstance創建實例,通過接口技術,則只要向程序集添加一個交通工具類,而不需要修改任何其它代碼..實現了高擴展性.,

創建泛型的實例:

// 先創建開放泛型 Type openType = typeof(List<>); // 再創建具象泛型 Type target = openType.MakeGenericType(new[] { typeof(string) }); // 最后創建泛型實例 List<string> result = (List<string>)Activator.CreateInstance(target);

 

System.Activator

System.Activator類中提供了三組靜態方法來創建類型的實例,每組方法均提供多個重載,適用不同的場景。個別重載方法返回ObjectHandle對象,需要unwrap后才能獲取對象實例。

CreateInstance :使用最符合指定參數的構造函數創建指定類型的實例。

CreateInstanceFrom :使用指定的程序集文件和與指定參數匹配程度最高的構造函數來創建指定名稱的類型的實例。

 

以下實例代碼演示了如何使用上述方法創建對象實例:

public class Employee
{
    public String Name { get; set; }
    public Employee(String name)
    {
        Name = name;
    }

    public Employee ()
    {
    }

    public void Say(String greeting)
    {
        Console.WriteLine(String.Format("Employee {0} say: {1} ", Name, greeting));
    }
}
// 使用無參構造函數
var employee = (Employee)Activator.CreateInstance(typeof(Employee));
employee.Say("CreateInstance with default ctor");

// 使用有參構造函數
employee=(Employee)Activator.CreateInstance(typeof(Employee), new object[] { "David" });
employee.Say("CreateInstance with ctor with args");
            
string assembly ="Test, Version=1.0.4562.31232, Culture=neutral, PublicKeyToken=null";
string type="Test.Tests.Employee";
var employeeHandle = Activator.CreateInstance(assembly,type);
employee = (Employee)employeeHandle.Unwrap();
employee.Say("CreateInstance and unwrap.");
            
string assemblyPath=@"E:\StudyProj\ShartDev\Test\Test\bin\Debug\Test.exe";
employeeHandle = Activator.CreateInstanceFrom(assemblyPath,type);
employee = (Employee)employeeHandle.Unwrap();
employee.Say("CreateInstanceFrom and unwrap.");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM