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

后端 未结 7 1206
渐次进展
渐次进展 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:26

    typeof(foo) is converted into a constant during compiletime. foo.GetType() happens at runtime.

    typeof(foo) also converts directly into a constant of its type (ie foo), so doing this would fail:

    public class foo
    {
    }
    
    public class bar : foo
    {
    }
    
    bar myBar = new bar();
    
    // Would fail, even though bar is a child of foo.
    if (myBar.getType == typeof(foo))
    
    // However this Would work
    if (myBar is foo)
    

提交回复
热议问题