C#中的反射有点偏门,它是一种可以访问、检测和修改程序本身状态或行为的一种能力.在程序的运行期间可以获取Assembly
,Module
,Class
中的相关信息.
反射的优点包括:
- 提高了程序的灵活性和扩展性.
-
减少了程序的耦合程度.
-
方便开发人员的调试.
但是这也是有代价的,因为反射有点类似Java的中间层,它也是一种解释型的操作,因此对于高并发/高性能的程序上,并不推荐使用;并且反射会使得代码逻辑变得更加难以维护.
using System;
using System.Reflection;
public class Info
{
private string qq;
private string phone;
private string address;
public string QQ {
get { return qq; }
set
{
if (value.Length > 5)
{
qq = value;
}
}
}
public string Phone
{
set
{
if(value.Length == 11)
{
phone = value;
}
}
get
{
return phone;
}
}
public string Address
{
set
{
if(value.Length != 0)
{
address = value;
}
}
get
{
return address;
}
}
private void someFunc()
{
Console.WriteLine("this is a private function.");
}
}
class Program
{
static void Main(string[] args)
{
Type itype1 = typeof(Info);
// 如果存在类型实例则可以使用GetType()获取Type
Info info = new Info();
Type itype2 = info.GetType();
MethodInfo[] methodInfos = itype1.GetMethods();
foreach(var i in methodInfos)
{
Console.WriteLine("方法:"+i.Name);
}
PropertyInfo[] propertyInfos = itype2.GetProperties();
foreach (var i in propertyInfos)
{
Console.WriteLine("属性:"+i.Name);
}
FieldInfo[] fieldInfos = itype1.GetFields();
foreach(var i in fieldInfos)
{
Console.WriteLine("字段:" + i.Name);
}
}
}