欢迎您来到“名字什么都是浮云”的博客空间!

Activator 动态构造对象

Activator 

意义:

用于动态构造对象

语法1:

根据指定的泛型类型构造对象

Activator.CreateInstance<类型>()

语法2:

根据程序集和类型名构造对象   

System.Runtime.Remoting.ObjectHandle oh =  Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, typeof(类型).FullName);

返回对象

(类型)oh.Unwrap();

示例:

using System;
using System.Reflection;
using System.Text;

public class SomeType
{
    public void DoSomething(int x)
    {
        Console.WriteLine("100 / {0} = {1}", x, 100 / x);
    }
}

public class Example
{
    static void Main()
    {
        // 根据指定的泛型类型构造对象    语法:Activator.CreateInstance<类型>()
        StringBuilder sb = Activator.CreateInstance<StringBuilder>();
        
        sb.Append("Hello, there.");
        Console.WriteLine(sb);

        // 根据程序集和类型名构造对象    语法:System.Runtime.Remoting.ObjectHandle oh =  Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, typeof(类型).FullName);
        System.Runtime.Remoting.ObjectHandle oh =  Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, typeof(SomeType).FullName);

        // 返回对象 语法:(类型)oh.Unwrap();
        SomeType st = (SomeType)oh.Unwrap();

        st.DoSomething(5);
    }
}

/* Main方法输出信息

Hello, there.
100 / 5 = 20
*/

 

posted @ 2017-09-01 11:01  名字什么都是浮云  阅读(237)  评论(0)    收藏  举报