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

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

    Provided you know all required types at compile-time, duck typingis (sort of) possible:

    class BarFoo {}
    class Foo {}
    class Bar {}
    
    class Program
    {
        static void Main( )
        {
            var foo = new Foo( );
            var bar = new Bar( );
            var barfoo = new BarFoo( );
    
            Console.WriteLine(DoStuff(foo));
            Console.WriteLine(DoStuff(bar));
            Console.WriteLine(DoStuff(barfoo));
    
        }
    
        static string DoStuff(Foo foo) { return "DoStuff(Foo foo)"; }
        static string DoStuff(Bar bar) { return "DoStuff(Bar bar)"; }
        static string DoStuff(Base fb) { return "DoStuff(object fb)"; }
    }
    

    Output:

    Dostuff(Foo foo)
    Dostuff(Bar bar);
    DoStuff(object fb);
    

    If you end up implementing a lot of methods that basically do exactly the same, consider implementing an interface.

提交回复
热议问题