Why is typeof needed?

后端 未结 6 1350
独厮守ぢ
独厮守ぢ 2021-01-12 14:57

Something I\'ve been thinking about from time to time: Why is the typeof operator needed in C#? Doesn\'t the compiler know that public class Animal is a type ju

相关标签:
6条回答
  • 2021-01-12 15:04

    Well, how do you get the System.Type of a class without instantiating the class first, if you don't use the typeof operatore? Simple, you can't :D

    Since you can do a lot of reflection stuff with just a System.Type, this operator is very handy.

    0 讨论(0)
  • 2021-01-12 15:11

    Not having typeof does cause ambiguity:

    class foo
    {
        public static string ToString()
        {
            return "Static";
        }
    }
    public class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine(foo.ToString());
            Console.WriteLine(typeof(foo).ToString());
        }
    }
    

    foo and typeof(foo) are not referring to the same thing, and forcing the compiler to pretend they are is a bad idea, even if we ignore this ambiguity.

    0 讨论(0)
  • 2021-01-12 15:11

    typeof() allows me to get an instance of a Type object without having to have an instance of the target object in hand. This in turn lets me ask questions about the class without having an instance of it.

    0 讨论(0)
  • 2021-01-12 15:13

    typeof(Class) is the only way to express Type as a literal. When you write Class.SomeField you mean static field. When you write typeof(Class).SomeField you reference field of object of class Type that represents your class.

    0 讨论(0)
  • 2021-01-12 15:25

    Animal is simply the name of the type, typeof(Animal) returns the actual type object (System.Type instance). Sure, it may have been possibly just to have the type name returning the type object in code, but it makes the job a lot harder for the compiler/parser (recognising when a type name means typeof or something else) - hence the existence of the typeof keyword. It also arguably makes the code clearer to read.

    0 讨论(0)
  • Reflection for starters. Many possibilities become available when you can inspect the type itself, instead of just having to know what it exposes, or that it exists at all.

    0 讨论(0)
提交回复
热议问题