How does generic type inference work in C#?

↘锁芯ラ 提交于 2019-12-20 01:43:57

问题


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?


回答1:


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().




回答2:


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.



来源:https://stackoverflow.com/questions/4885027/how-does-generic-type-inference-work-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!