Is possible to cast a variable to a type stored in another variable?

前端 未结 5 966
别跟我提以往
别跟我提以往 2021-01-03 23:18

This is what I need to do:

object foo = GetFoo();
Type t = typeof(BarType);
(foo as t).FunctionThatExistsInBarType();

Can something like th

5条回答
  •  情书的邮戳
    2021-01-04 00:01

    Since dynamics were added to c#, I think we can do it in this way:

    class Program {
        static void Main(string[] args) {
            List c = new List(); 
            double i = 10.0;
            Type intType = typeof(int);
            c.Add(CastHelper.Cast(i, intType)); // works, no exception!
        }
    }
    
    class CastHelper {
        public static dynamic Cast(object src, Type t) {
            var castMethod = typeof(CastHelper).GetMethod("CastGeneric").MakeGenericMethod(t);
            return castMethod.Invoke(null, new[] { src });
        }
        public static T CastGeneric(object src) {
            return (T)Convert.ChangeType(src, typeof(T));
        }
    }
    

提交回复
热议问题