反射创建构造方法无参或带参类的实例对象
时间:2010-10-19 来源:arg
废话少说,直接上代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
Type personType = Type.GetType("ReflectionTest.Person",true);
//带参数
Type[] paramTypes = new Type[1];
paramTypes[0] = typeof(string);
ConstructorInfo ctiWithParam = personType.GetConstructor(paramTypes);
if (ctiWithParam != null)
{
object[] paramArr = new object[1];
paramArr[0] = "baobao";
Person p = ctiWithParam.Invoke(paramArr) as Person;
Console.WriteLine(p.Name);
}
//不带参数
ConstructorInfo ctiNoParam = personType.GetConstructor(Type.EmptyTypes);
if (ctiNoParam != null)
{
Person p = ctiNoParam.Invoke(null) as Person;
Console.WriteLine(p.Name);
}
Console.ReadKey();
}
}
class Person
{
public string Name { get; set; }
public Person()
{
Name = "beibei";
}
public Person(string name)
{
Name = name;
}
}
}
相关阅读 更多 +










