Activator 动态构造对象

时间:2023-03-08 23:50:39
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, / 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();
}
} /* Main方法输出信息 Hello, there.
100 / 5 = 20
*/