Generic method to type casting

前端 未结 8 1201
不思量自难忘°
不思量自难忘° 2021-02-02 11:55

I\'m trying to write generic method to cast types. I want write something like Cast.To(variable) instead of (Type) variable. My wrong versi

8条回答
  •  忘了有多久
    2021-02-02 12:06

    All of what's been said about the operator resolution is correct...but this is my answer to your main question:

        public static T To(this object o)
        {
            return (T)(dynamic)o;
        }
    

    The key here is that casting o to dynamic will force the .NET to search for the explicit operator at runtime.

    Plus, why not make it an extension method?

    Instead of

            A a = new A();
            B b = Cast.To(a);
    

    you can do

            A a = new A();
            B b = a.To();
    

    An added benefit of exposing it as an extension method is that you gain a fluent interface for explicit casting (if you like that sort of thing). I've always hated the amount of nested parenthesis balancing required for explicit casting in .NET.

    So you can do:

    a.To().DoSomething().To().DoSomethingElse() 
    

    instead of

    ((C)((B)a).DoSomething())).DoSomethingElse()
    

    which, to me, looks clearer.

提交回复
热议问题