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

前端 未结 5 925
别跟我提以往
别跟我提以往 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:19

    Your original question was flawed in that you ask to treat a variable as a type which is not known at compile time but note that you have string defined on the left hand side when you declare your variable. C# as of 3.5 is statically typed.

    Once dynamic is available you could do something like this:

    dynamic foo = GetFoo();
    foo.FunctionThatExistsInBarType(); 
    

    For when you don't know what the type is but you know it will always support the instance method FunctionThatExistsInBarType();

    for now you are forced to use reflection (or code gen which really amounts to much the same thing but more expensive up front and faster later).

    // any of these can be determined at runtime
    Type t = typeof(Bar);
    string methodToCall = "FunctionThatExistsInBarType";
    Type[] argumentTypes = new Type[0];
    object[] arguments = new object[0];
    object foo;
    // invoke the method - 
    // example ignores overloading and exception handling for brevity
    // assumption: return type is void or you don't care about it
    t.GetMethod(methodToCall, BindingFalgs.Public | BindingFlags.Instance)
        .Invoke(foo, arguments);
    

提交回复
热议问题