1.概要
方式1
Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集
Object[] objects = { "a" };
A a = (A)assembly.CreateInstance(t.FullName,true, BindingFlags.CreateInstance, null, objects, null, null);
方式2
Type type = Type.GetType(t.FullName);
A a = (A)Activator.CreateInstance(type, objects);
方式3
var c = type.GetConstructors();
Object[] objects = { "a" };
A a = (A)c[0].Invoke(objects);
2.代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace 根据类型名创建对象
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("根据类型名创建对象");
Program program = new Program();
program.main();
Console.ReadKey();
}
private void main() {
test1(typeof(A));
test2(typeof(A));
test3(typeof(A));
}
//只使用Assembly
private void test1(Type t) {
Console.WriteLine("只使用Assembly");
Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集
Object[] objects = { "a" };
A a = (A)assembly.CreateInstance(t.FullName,true, BindingFlags.CreateInstance, null, objects, null, null);
a.Fun();
}
//使用Activator和Type
private void test2(Type t)
{
Console.WriteLine("使用Activator和Type");
Object[] objects = { "a" };
{
//这种不行,因为这个值支持默认的构造函数
//A a = (A)Activator.CreateInstance(t.Namespace, t.FullName, objects).Unwrap();
}
Type type = Type.GetType(t.FullName);
A a = (A)Activator.CreateInstance(type, objects);
a.Fun();
}
//只使用Type
private void test3(Type t)
{
Console.WriteLine("只使用Type");
Type type = Type.GetType(t.FullName);
{
//这个不行 这是不包括构造函数吗?
//var b = type.GetMethod(t.Name);
}
var c = type.GetConstructors();
Object[] objects = { "a" };
A a = (A)c[0].Invoke(objects);
a.Fun();
}
}
public class A {
private string mA;
public A(string a) { mA = a; }
public void Fun() {
Console.WriteLine("我是A,我在运行"+ "mA:" + mA);
}
}
}
3.运行结果