开发者

Why is typeof needed?

开发者 https://www.devze.com 2023-01-05 10:02 出处:网络
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 t开发者_Python百科ype just by the very definiti

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 t开发者_Python百科ype just by the very definition? Why do I need to specify SomeMethod(typeof(Animal)) when I need to reference a type?


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.


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.


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.


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号