I have a problem with downcasting, how do I convert the string “Label” to the class type Label for casting and is it possible to reach the ‘Texts’ class?
public class GFXObject
{
// Constructor etc...
}
public class Label : GFXObject
{
public Texts Text = new TextClass();
// Constructor etc...
}
public class Button : GFXObject
{
// Constructor etc...
}
public class Texts
{
public string Text = "empty";
// Constructor etc...
}
// My List of objects
Dictionary<string, GFXObject> objects;
// Disregarding any troubleshooting
public void ChangeText(string classtype, string name, string text)
{
// How do I convert the string classtype to a ClassType
((classtype)objects[name]).Text.Text = text;
// If parameters would be equal to "Label", "label", "changed":
// ((Label)objects["label"].Text.Text = "changed";
}
Is it possible to use the ChangeText function if extended or modified?
You can do that only via reflection:
Please note that
classtypeneeds to be an assembly-qualified name if the method is in a different assembly than the type. If it is in the same assembly it needs to be fully qualified, i.e. including the namespace.If that’s a problem, you could get rid of the
classtypeparameter and use this method:Another possibility would be to make use of the DLR and the
dynamickeyword:Please note that every code that uses the dynamic
itemvariable is evaluated only at runtime. This means that this code compiles even if there is noTextproperty on that particular item. It will then throw an exception at runtime.Having said all that, the correct solution to this problem would be to introduce a base class or interface that holds the
Textproperty.