希望是一个足够简单的问题,但我正在努力寻找答案。
如何将“对象”转换为“类型”对象中定义的类型。
例如,基本上我正在尝试通过反射执行以下操作,使其尽可能通用:
public class MyClass
{
public string Prop1 { get; set; }
public int Prop2 { get; set; }
}
public T FillMyClass<T>() where T : new()
{
//The definitions here are suppled in code - each class we want to work with needs to be "mapped".
string name1 = "Prop1";
Type type1 = typeof(string);
string name2 = "Prop2";
Type type2 = typeof(int);
//The values always start out as a string because of the way I'm receiving it.
string val1 = "test";
string val2 = "1";
T t= new T();
//Works fine, because val1 is already a string
t.GetType().GetProperty(name1).SetValue(t, val1, null);
//Having trouble with the below.
object o = Convert.ChangeType(val2, type2);
//Fails because o is not an int
t.GetType().GetProperty(name2).SetValue(t, o, null);
}
所以类型是由用户定义的(或者甚至可能只是通过查找属性的类型)。但我只是看不到如何将对象转换为 [Type]。