What is the difference between myCustomer.GetType() and typeof(Customer) in C#?

后端 未结 7 1210
渐次进展
渐次进展 2020-12-02 07:11

I\'ve seen both done in some code I\'m maintaining, but don\'t know the difference. Is there one?

let me add that myCustomer is an instance of Customer

7条回答
  •  天命终不由人
    2020-12-02 07:28

    The typeof operator takes a type as a parameter. It is resolved at compile time. The GetType method is invoked on an object and is resolved at run time. The first is used when you need to use a known Type, the second is to get the type of an object when you don't know what it is.

    class BaseClass
    { }
    
    class DerivedClass : BaseClass
    { }
    
    class FinalClass
    {
        static void RevealType(BaseClass baseCla)
        {
            Console.WriteLine(typeof(BaseClass));  // compile time
            Console.WriteLine(baseCla.GetType());  // run time
        }
    
        static void Main(string[] str)
        {
            RevealType(new BaseClass());
    
            Console.ReadLine();
        }
    }
    // *********  By Praveen Kumar Srivastava 
    

提交回复
热议问题