Type类在System.Reflection命名空间下,通过它可以得到类的一些信息.
通过对象.GetType()获取对象的类型信息.
IsPrimitive.注意此属性是获取当前类型是否为基元类型,如:byte,short,int...string,object等.
IsNestedPrivate:是否是私有类.
GetFields();获取公有字段信息.
GetProperties();获取公有属性.
GetMethods();获取公有方法.
测试代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Reflection;
namespace ConsoleApplication2
{
class Program
{
private class TestReflection
{
private int m_age;
public int m_Age
{
get
{
return m_age;
}
set
{
m_age = value;
}
}
private int m_PriPro
{
get
{
return 233;
}
set
{
}
}
public string m_name;
public void WriteLine (string str)
{
PriWriteLine(str);
}
private void PriWriteLine (string str)
{
Console.WriteLine(str);
}
}
static void Main(string[] args)
{
TestReflection m_test = new TestReflection();
Type m_tp = m_test.GetType();
Console.WriteLine("IsPublic: {0}", m_tp.IsPublic);
Console.WriteLine("IsSealed: {0}", m_tp.IsSealed);
Console.WriteLine("IsPrimitive: {0}", m_tp.IsPrimitive);
Console.WriteLine("IsNestedPrivate: {0}", m_tp.IsNestedPrivate);
Console.WriteLine("-------------------------------------------------");
int num = 1;
Type m_numTp = num.GetType();
Console.WriteLine("m_numTp IsPrimitive: {0}", m_numTp.IsPrimitive);
Console.WriteLine("-------------------------------------------------");
FieldInfo[] fieldInfos = m_tp.GetFields();
for (int i = 0; i < fieldInfos.Length; i++)
{
Console.WriteLine("fieldInfos[{0}]:{1}", i, fieldInfos[i].Name);
}
Console.WriteLine("-------------------------------------------------");
PropertyInfo[] propertyInfos = m_tp.GetProperties();
for (int i = 0; i < propertyInfos.Length; i++)
{
Console.WriteLine("propertyInfos[{0}]:{1}", i, propertyInfos[i].Name);
}
Console.WriteLine("-------------------------------------------------");
MethodInfo[] methodInfos = m_tp.GetMethods();
for (int i = 0; i < methodInfos.Length; i++)
{
Console.WriteLine("methodInfos[{0}]:{1}", i, methodInfos[i].Name);
}
}
}
}
打印信息: