Generic method to type casting

前端 未结 8 1131
不思量自难忘°
不思量自难忘° 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:21

    I've actually encountered this problem more than once and it doesn't feel as OOP "dirty" when I can limit myself to types implementing the IConvertible interface. Then the solution actually becomes very clean!

    private T To(object o) where T : IConvertible
    {
        return (T)Convert.ChangeType(o, typeof(T));
    }
    

    I've used a variation of this when I for example wrote a tokenizer, where the input was a string, but where the tokens could be interpreted as both strings, integers, and doubles.

    Since it's using the Convert class, the compiler will actually have information to know what to do. It's not just a simple cast.

    If you need an even more generic way of casting, I have to wonder if this is not rather a design problem in code. I think a problem with broadening the scope for these things, is that the more areas you try to cover, the harder it will be for an outsider to know how much the method can do.

    I think it's of utmost importance that the casting actually works out when someone has specifically written a method for the job to avoid a situation like Add(x, y) for only certain values of x and y.

    I think the expectation is different if you try the casting yourself, as in T1 x = (T1) T2 y. Then I think it's more apparent that you're truly on your own, since you just made up some cast rather than called a "cover all casts method".

    In this case, it's clear that it's specifically dealing with objects implementing IConvertible and the developer can assume it'll work well with any of these objects.

    Maybe an object oriented-philosophy heavy answer that not everyone will even agree with, but I think these kinds of "conceptual questions" often end up in programming philosophy.

提交回复
热议问题