不知是周经,月经,年经,反正是来了(没有来,更吓人),或者是剩饭,馊饭,炒饭,可以匆匆飘过。
废话少说,直接上代码:
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);
#region 带参数
//依据传入参数获取特定构造方法
Type[] paramTypes = new Type[1];
//string stringP = "baobao";
int intP = 10;
//paramTypes[0] = stringP.GetType();
paramTypes[0] = intP.GetType();
ConstructorInfo ctiWithParam = personType.GetConstructor(paramTypes);
object[] paramArr = new object[1];
//paramArr[0] = stringP;
paramArr[0] = intP;
if (ctiWithParam != null)
{
Person p = ctiWithParam.Invoke(paramArr) as Person;
Console.WriteLine(p.Name);
}
//依据构造方法的自我描述(ParameterInfo),创建实例
paramArr[0] = "baobao";
ConstructorInfo[] ctis = personType.GetConstructors();
ConstructorInfo cti = ctis.Single<ConstructorInfo>(
delegate(ConstructorInfo item)
{
ParameterInfo[] paramInfos = item.GetParameters();
return paramInfos != null && paramInfos.Length > 0 && paramInfos[0].ParameterType == typeof(string);
});
if (cti != null)
{
Person p = cti.Invoke(paramArr) as Person;
Console.WriteLine(p.Name);
}
#endregion
#region 不带参数
ConstructorInfo ctiNoParam = personType.GetConstructor(Type.EmptyTypes);
if (ctiNoParam != null)
{
Person p = ctiNoParam.Invoke(null) as Person;
Console.WriteLine(p.Name);
}
#endregion
Console.ReadKey();
}
}
class Person
{
public string Name { get; set; }
public int Id { get; set; }
public Person()
{
Name = "beibei";
}
public Person(string name)
{
Name = name;
}
public Person(int i)
{
Id = i;
Name = i.ToString();
}
}
}
ps:
System.Activator更强大,看msdn描叙:
包含特定的方法,用以在本地或从远程创建对象类型,或获取对现有远程对象的引用。
Activator提供的方法简单明了,不再赘述。