简体   繁体   中英

How does generic type inference work in C#?

If I have the following code

private BaseMessage getMessage()
{
    return new OtherMessage();
}

private void CheckType<T>(T type)
{
    Console.WriteLine(type.GetType().ToString());
    Console.WriteLine(typeof(T).ToString());
}

private void DoChecks()
{
     BaseMessage mess = getMessage();
     CheckType(mess);
}

why do I get different types outputted? Is there anyway of getting the type inference to use the actual type of the object being passed?

Generic type inference means that the compiler automatically resolves the types of the arguments being passed without the need of you explicitly specifying what type you're passing. This means that this is done in compile-time: in your code, during the compilation, the compiler only knows about BaseMessage, so the parameter will be passed as BaseMessage. During the run-time, the parameter's actual type will be OtherMessage, but that is of no concern to the compiler.

Therefore, the output you're getting is absolutely valid. I don't know any ways do overcome this issue, apart from always using Object.GetType instead of typeof().

The reason is that you've declared the variable mess as being of type BaseMessage . So when you ask for the type, it's returning BaseMessage .

It's a difference between the way that GetType and typeof behave. GetType returns the actual type of the object at run-time, which can be different from the type of the variable that references the object if inheritance is involved (as is the case in your example). Unlike GetType , typeof is resolved at compile-time to a type literal of the exact type specified.

public class BaseMessage { }

public class OtherMessage : BaseMessage { }

private BaseMessage getMessage()
{
    return new OtherMessage();
}

private void CheckType<T>(T type)
{
    Console.WriteLine(type.GetType().ToString());   // prints OtherMessage
    Console.WriteLine(typeof(T).ToString());        // prints BaseMessage
}

private void DoChecks()
{
     BaseMessage mess = getMessage();
     CheckType(mess);
}

You have to choose the right tool for the job. Use typeof when you want to get the type at compilation time. Use GetType when you want to get the run-time type of an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM