How to cast object to type described by Type class?

前端 未结 5 610
旧时难觅i
旧时难觅i 2020-12-10 00:35

I have a object:

ExampleClass ex = new ExampleClass();

And:

Type TargetType

I would like to cast ex to ty

5条回答
  •  一个人的身影
    2020-12-10 01:14

    Object o = (TargetType) ex;
    

    This code is useless. You might have a type on the right but it's still only an object on the left side. You can't use functionality specific to TargetType like this.


    This is how you can invoke a method of an unknown object of a given type:

    object myObject = new UnknownType();
    Type t = typeof(UnknownType); // myObject.GetType() would also work
    MethodInfo sayHelloMethod = t.GetMethod("SayHello");
    sayHelloMethod.Invoke(myObject, null);
    

    With this UnknownType class:

    class UnknownType
    {
        public void SayHello()
        {
            Console.WriteLine("Hello world.");
        }
    }
    

提交回复
热议问题