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

后端 未结 3 1964
栀梦
栀梦 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:31

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

    0 讨论(0)
  • 2020-12-06 06:33

    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;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题