Is there a way to do dynamic implicit type casting in C#?

送分小仙女□ 提交于 2019-11-27 22:59:57

Am I correct?

Yes, yes you are. To be nit-picky, you should be saying "user-defined implicit conversion" rather than "implicit cast" -- a cast is (almost) always explicit. But your deduction that overload resolution chooses which user-defined conversion to call at compile time and not at run time is correct.

Is there some other way to do this?

Yes. In C# 4 if you type your "object" as "dynamic" then we start up the compiler again at runtime and re-perform all the analysis on the operands as though their compile-time types were the current run-time types. As you might imagine, this is not cheap, though we are very smart about caching and re-using the results should you do this in a tight loop.

I know this is an older question but in case anyone else stumbles upon the same problem, this will compile and run fine:

long f = 5;
object g = f;
MyDateTime h = g as MyDateTime;

Adding an explicit operator should work: http://msdn.microsoft.com/en-us/library/85w54y0a(VS.80).aspx

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