<1>
TypeOf()与GetType()的区别
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace @typeof
{
// TypeOf() 和 GetType()的区别:
//<1> TypeOf():得到一个Class的Type
//<2> GetType():得到一个Class的实例的Type
//Typeof()是运算符而GetType是方法
//GetType()是基类System.Object的方法,因此只有建立一个实例之后才能够被调用(初始化以后)
//Typeof()的参数只能是int,string,String,自定义类型,且不能是实例
class Program
{
static void Main(string[] args)
{
//得到一个Class的Type
var type = typeof(int);
Console.WriteLine(type); //输出System.int32
//得到一个Class的Type
var type3 = typeof(Program);
Console.WriteLine(type3); //输出typeof.Program
//-----------------------------------------------------------
Program p = new Program();
//得到一个Class的实例的Type
var type2= p.GetType();
Console.WriteLine(type2); //输出typeof.Program
Console.ReadKey();
}
}
}
<.2>
获取对象类型的所有公有属性。GetProperties() 和所有公有方法GetMethods()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace StringBuilders
{
class User
{
public User()
{
}
public void GetData()
{
}
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
private string Gender { get; set; }
}
class Program
{
static void Main(string[] args)
{
User u = new User();
//获取u对象类型的所有公有属性。 即:获取User类的所有公有属性 它的返回值是PropertyInfo类型的数组
PropertyInfo[] strObject = u.GetType().GetProperties();
//获取User类的所以公有属性 (与上面那句代码效果一致)
var strClass = typeof(User).GetProperties();
foreach (PropertyInfo v in strObject) //遍历User类的所有公有属性
{
Console.WriteLine(v.Name);
}
Type c = typeof(User);
//获取Type类型的所以公有方法。返回值是一个MethodInfo类型的数组
MethodInfo[] methods = c.GetMethods();
foreach (MethodInfo m in methods) //遍历User类的所有公有方法
{
Console.WriteLine(m.Name);
}
Console.ReadKey();
}
}
}
<3>
获取一个类实例的类型 GetType()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class User
{
public string UserName { get; set; }
}
class Program
{
static void Main(string[] args)
{
User u = new User(); //创建一个User类的对象 u
Type t = u.GetType(); //获取 这个u对象的类型
Console.WriteLine(t); //输出ConsoleApplication1.User
Console.ReadKey();
}
}
}