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

后端 未结 3 1973
栀梦
栀梦 2020-12-06 05:57

Given this class with an implicit cast operator:

public class MyDateTime
{
    public static implicit operator MyDateTime(System.Int64 encoded)
    {
                


        
3条回答
  •  离开以前
    2020-12-06 06:36

    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.

提交回复
热议问题