1.概要
方式1
Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集
A a = (A)assembly.CreateInstance(t.FullName);
方式2
A a = (A)Activator.CreateInstance(t.Namespace, t.FullName).Unwrap();
方式3
Type type = Type.GetType(t.FullName);
A a = (A)c[0].Invoke(null);
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(); // 获取当前程序集
A a = (A)assembly.CreateInstance(t.FullName);
a.Fun();
}
//使用Activator和Type
private void test2(Type t)
{
Console.WriteLine("使用Activator和Type");
A a = (A)Activator.CreateInstance(t.Namespace, t.FullName).Unwrap();
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();
{
//这种不行 应该是参数不对
//A a = (A)type.GetMethod(t.Name).Invoke(null,null);
}
A a = (A)c[0].Invoke(null);
a.Fun();
}
}
public class A {
public A() { }
public void Fun() {
Console.WriteLine("我是A,我在运行");
}
}
}
3.运行