就是对未知的类型进行各种特定的操作.Reflection的核心是Type. 也就是类型信息。 通过Type,可以得到该类型相关的信息: 字段(FieldInfo),例如 public int Length; 属性(PropertyInfo),例如 public string Name{get;} 方法(MethodInfo),例如 public void Write(string str); ... 类型的信息,例如: 是class,struct,interface,enum...的哪种? 是不是public的,基类是什么等。. 更多的就不说了。就是这些信息的访问了。但是具体用在哪里,实在是很难说得请。 因为Reflection是语言功能的补充。 一般的应用,根本不需要Reflection.不过常规应用的例子还是可以举的:你创建了一个类 public enum SexType { Boy,Girl } public class StudentInfo { public string Name; public int Age; public SexType Sex; } 然后你用这个方法来显示它的属性: public virtual void ShowInfo(StudentInfo si) { Console.WriteLine("Name:\t"+si.Name); Console.WriteLine("Age:\t"+si.Age); Console.WriteLine("Sex:\t"+si.Sex); } 但是,如果有人扩充了你的类: public StudentInfoEx:StudentInfo { public string FatherName; public string MotherName; } 那么在上面的ShowInfo不变的情况下,怎样显示扩充了的内容呢? 当然,可以这样: public override void ShowInfo(StudentInfo si) { base.ShowInfo(si); if(si is StudentInfoEx) { StudentInfoEx siex=(StudentInfoEx)si; Console.WriteLine(siex.FatherName); Console.WriteLine(siex.MotherName); } }当然,如果你懒点,在原方法定义时就用Reflection:public virtual void ShowInfo(StudentInfo si) { Type t=si.GetType(); foreach(FieldInfo fi in t.GetFields(BindingFlags.Instance|BindingFlags.Public)) { Console.WriteLine(fi.Name+":\t"+fi.GetValue(si)); } }当然.上面的例子写简单了。实际上做反射的编程,要考虑很多东西。 例如fi.GetValue可能会返回null,或者抛出异常等。
也就是类型信息。
通过Type,可以得到该类型相关的信息:
字段(FieldInfo),例如 public int Length;
属性(PropertyInfo),例如 public string Name{get;}
方法(MethodInfo),例如 public void Write(string str);
...
类型的信息,例如:
是class,struct,interface,enum...的哪种?
是不是public的,基类是什么等。.
更多的就不说了。就是这些信息的访问了。但是具体用在哪里,实在是很难说得请。
因为Reflection是语言功能的补充。
一般的应用,根本不需要Reflection.不过常规应用的例子还是可以举的:你创建了一个类
public enum SexType
{
Boy,Girl
}
public class StudentInfo
{
public string Name;
public int Age;
public SexType Sex;
}
然后你用这个方法来显示它的属性:
public virtual void ShowInfo(StudentInfo si)
{
Console.WriteLine("Name:\t"+si.Name);
Console.WriteLine("Age:\t"+si.Age);
Console.WriteLine("Sex:\t"+si.Sex);
}
但是,如果有人扩充了你的类:
public StudentInfoEx:StudentInfo
{
public string FatherName;
public string MotherName;
}
那么在上面的ShowInfo不变的情况下,怎样显示扩充了的内容呢?
当然,可以这样:
public override void ShowInfo(StudentInfo si)
{
base.ShowInfo(si);
if(si is StudentInfoEx)
{
StudentInfoEx siex=(StudentInfoEx)si;
Console.WriteLine(siex.FatherName);
Console.WriteLine(siex.MotherName);
}
}当然,如果你懒点,在原方法定义时就用Reflection:public virtual void ShowInfo(StudentInfo si)
{
Type t=si.GetType();
foreach(FieldInfo fi in t.GetFields(BindingFlags.Instance|BindingFlags.Public))
{
Console.WriteLine(fi.Name+":\t"+fi.GetValue(si));
}
}当然.上面的例子写简单了。实际上做反射的编程,要考虑很多东西。
例如fi.GetValue可能会返回null,或者抛出异常等。