Why is typeof needed?

后端 未结 6 1389
独厮守ぢ
独厮守ぢ 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: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.

提交回复
热议问题