In my application, I'm using a package that reads a specific type of file (let's say .custom) that describes a house. It has custom types to describe objects (t_doors and t_windows to keep it simple)
This package has a function Reader.GetAll<t_type>() that gives me all the objects of said type in the file, and a Reader.GetItem<t_type>(int itemId) that gives me a specific t_type object with itemId ID.
Now i'm reading a list of required updates from a user-provided file that includes the type, the id and the changes in the form of a List<List<string>>
. This part is outside my control.
I need to be able to read the type from the string and pass it to my generic function.
So far I've tried :
var r = new List<string>(){ "t_door", "1", "Color:Red" };
Type T = Type.GetType(r[0]);
ModifyProperties<T>(r[1], r[2]);
'T' is a variable but is used like a type.
Same error with:
ModifyProperties<typeof(T)>(r[1], r[2]);
And :
ModifyProperties<T.GetType()>(r[1], r[2]);
Operator '<' cannot be applied to operands of type 'method groups' and 'Type'
Here is the signature of the ModifyProperties function :
public static void ModifyProperties<ObjectTypeToEdit>(string id, string modification) where ObjectTypeToEdit : t_object
So far my workaround has been to use a switch on the type and call the method with the correct type :
switch (r[0])
{
case "t_door":
ModifyProperties<t_door>(r[1], r[2]);
break;
case "t_window":
ModifyProperties<t_window>(r[1], r[2]);
break;
...
}
Which is far from ideal considering there are hundreds of types of objects that could possibly be required.
Also i read something about an Activator class but i'm not sure how it would help.
Same with reflections :
object obj = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(r[0]);