うまくいけば、十分に単純な質問ですが、答えを見つけるのに苦労しています。
「オブジェクト」を「タイプ」オブジェクトで定義されたタイプにキャストするにはどうすればよいですか。
たとえば、基本的に、リフレクションを使用して次のことを行い、可能な限り一般的にしようとしています。
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] にキャストする方法がわかりません。