vendredi 21 juillet 2017

How to convert an Object by the type name and pass it as an argument to another method

here is my code:

using System.Reflection;
Public class ClassA
{
    public ClassA()
    {
        ClassB classB = new ClassB();
        classB.UsingType = "ClassD";
        ClassB.Do();
    }
}
Public class ClassB
{
    public string UsingType { get; set; }
    public void Do()
    {
        ClassC classC = new ClassC();
        Type type = Type.GetType(UsingType);
        Object obj = Activator.CreateInstance(type);
        classC.Do(obj); // Error : cannot convert from 'object' to 'ClassD'
    }
}
public class ClassC
{
    public void Do(ClassD classD) // If I change "ClassD" to "Object" It works!!
    {
        //Do something with classD
    }
}

I get this error: "cannot convert from 'object' to 'ClassD'."

If I change "Do" method argument of "ClassC" from "ClassD" to "Object" the error goes away and then I can cast it to "ClassD" and use that parameter. But that's not what I want.

Is there a way to cast "obj" by "UsingType" string to "ClassD" (in "Do" method of "ClassB") and get rid of the compile time error?

In other words: (since "ClassA" knows the type name string and passes it to "ClassB") how can I cast from "Object" to the type that "ClassC" asks for?





Aucun commentaire:

Enregistrer un commentaire