Cast with GetType()

后端 未结 5 1904
无人及你
无人及你 2020-12-15 03:13

Is it possible to cast an object to the type returned from GetType()? I\'d like a generic method that can accept an object (for anonymous types) but then return

5条回答
  •  温柔的废话
    2020-12-15 03:50

    I can't think of why you'd want to cast as GetType(), because you wouldn't be able to do anything to useful with the result, without knowing the type at compile time anyway.

    Perhaps what you are looking for, is being able to Convert. If that is the case, the following should work for you:

    object input = GetSomeInput();
    object result = Convert.ChangeType(input, someOtherObject.GetType());
    

    We use this when reading values from the registry which are all stored as strings, and then stuffing them into properties using reflection.

提交回复
热议问题