C#: Dynamic runtime cast

前端 未结 9 2212
情深已故
情深已故 2020-11-27 03:50

I would like to implement a method with the following signature

dynamic Cast(object obj, Type castTo);

Anyone know how to do that? obj defi

9条回答
  •  悲&欢浪女
    2020-11-27 04:16

    This should work:

    public static dynamic Cast(dynamic obj, Type castTo)
    {
        return Convert.ChangeType(obj, castTo);
    }
    

    Edit

    I've written the following test code:

    var x = "123";
    var y = Cast(x, typeof(int));
    var z = y + 7;
    var w = Cast(z, typeof(string)); // w == "130"
    

    It does resemble the kind of "typecasting" one finds in languages like PHP, JavaScript or Python (because it also converts the value to the desired type). I don't know if that's a good thing, but it certainly works... :-)

提交回复
热议问题