C#: Dynamic runtime cast

前端 未结 9 2217
情深已故
情深已故 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 03:53

    Best I got so far:

    dynamic DynamicCast(object entity, Type to)
    {
        var openCast = this.GetType().GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic);
        var closeCast = openCast.MakeGenericMethod(to);
        return closeCast.Invoke(entity, new[] { entity });
    }
    static T Cast(object entity) where T : class
    {
        return entity as T;
    }
    

提交回复
热议问题