typeof和GetType()获取Type类型

typeof

typeof是运算符,获取某一类型的 System.Type 对象。 typeof()的参数只能是int,string,String,自定义类型,且不能是实例。 Type t = typeof(int);

GetType()

方法,获取当前实例的类型 int i = 10; Console.WriteLine(i.GetType());

typeof和GetType的联系和区别

Typeof()是运算符而GetType是方法 GetType()是基类System.Object的方法,因此只有建立一个实例之后才能够被调用(初始化以后) Typeof()的参数只能是int,string,String,自定义类型,且不能是实例 具体代码示例:

class Program
{
    public int TestMember;
    public void SampleMethod() {}
    public int TestInt()
    {
        return 0;
    }
    static void Main(string[] args)
    {
        Type t = typeof (Program);
        Console.WriteLine("属性:");
        Console.WriteLine(t.Name);
        Console.WriteLine(t.FullName);
        Console.WriteLine(t.Assembly);
        Console.WriteLine(t.IsAbstract);
        Console.WriteLine(t.IsEnum);
        Console.WriteLine(t.IsClass);
        Console.WriteLine("方法:");
        MethodInfo[] methodInfos = t.GetMethods();
        foreach (MethodInfo mInfo in methodInfos)
            Console.WriteLine(mInfo.ToString());
 
        Console.WriteLine("成员:");
        MemberInfo[] memberInfo = t.GetMembers();
        foreach (MemberInfo mInfo in memberInfo)
            Console.WriteLine(mInfo.ToString());
        Console.ReadKey();
    }
}

 

posted @ 2020-04-03 14:13  风雪江山  阅读(766)  评论(0编辑  收藏  举报