简体   繁体   中英

Cast to type from Type variable

I use Unity. I have an

abstract class A {}
class A1 : A {object someField;}
class A2 : A {object someField;}

I have a CustomEditor where I create instances of A1/A2 with reflection (I need an ability to add new classes derived from A) But there is a problem: if I use Activator like

Type chosenType = ChooseType(); //ChosenType can be A1 or A2
A newObj = (A)Activator.CreateInstance(chosenType)

Unity doesnt serialize that objects (because it serialize objects as (A) but not as (A1) or (A2)) I want to cast like

(chosenType)MyObj

The best way I've seen to dynamically do type casting like this is to create a generic like

public static class ReflectionHelper{

    public T CastTo<T>(object obj)
    {
        return (T) obj;
    }
}

And then to at runtime, create a generic method to cast to my specific type.

var value = Activator.CreateInstance(ChosenType());
typeof(ReflectionHelper)
.GetMethod("CastTo")
.MakeGenericMethod(new []{value.GetType()})
.Invoke(null, value);

In invoke, we call null because it's a static method, if it was an instance method we would need an instance of an object of type Reflection Helper.

However, I want to warn you doing these things tend to be a code smell, and I would urge you to only use reflection as your last resort not as your first go-to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM