您的位置:首页 > 其它

反射:Type and Reflection

2009-06-09 11:52 176 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace House
{
public class Class1
{
private string name;
private int age;
public Class1(string Name, int Age)
{
name = Name;
age = Age;
}
public void ChangeName(string NewName)
{
name = NewName;
}
public void ChangeAge(int NewAge)
{
age = NewAge;
}
public override string ToString()
{
return string.Format("Name: {0}, Age: {1}", name, age);
}

}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Assembly tmpAss = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "House.dll");
Type[] tmpTypes = tmpAss.GetTypes();
foreach (Type tmpType in tmpTypes)
{
ConstructorInfo[] tmpConsInfos = tmpType.GetConstructors();
foreach (ConstructorInfo tmpConsInfo in tmpConsInfos)
{
ParameterInfo[] tmpParamInfos = tmpConsInfo.GetParameters();
object[] tmpParams = new object[tmpParamInfos.Length];
for (int i = 0; i < tmpParamInfos.Length; i++)
{
tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName);
if (tmpParamInfos[i].ParameterType.FullName == "System.String")
{
tmpParams[i] = "Clark";
}
}
object tmpObj = tmpConsInfo.Invoke(tmpParams);
Console.WriteLine(tmpObj);
foreach (MethodInfo tmpMethod in tmpType.GetMethods())
{
tmpParamInfos = tmpMethod.GetParameters();
tmpParams = new object[tmpParamInfos.Length];
for (int i = 0; i < tmpParamInfos.Length; i++)
{
tmpParams[i] = tmpAss.CreateInstance
(tmpParamInfos[i].ParameterType.FullName);

if (tmpParamInfos[i].ParameterType.FullName == "System.String")
{
tmpParams[i] = "Clark Zheng";
}
if (tmpParamInfos[i].ParameterType.FullName == "System.Int32")
{
tmpParams[i] = 27;
}
}
tmpMethod.Invoke(tmpObj, tmpParams);
}
Console.WriteLine(tmpObj);
Console.ReadKey();
}
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐