替代标题:在运行时动态转换为类型。
我想将 Object 转换为将在运行时分配的类型。
例如,假设我有一个将字符串值(来自 a TextBox or Dropdownlist
)分配给 a 的函数Object.Property
。
如何将值转换为正确的类型?例如,它可以是整数、字符串或枚举。
Public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type t= obj.GetType().GetProperty(propName).PropertyType;
//Now Setting the property to the value .
//But it raise an error,because sometimes type is int and value is "2"
//or type is enum (e.a: Gender.Male) and value is "Male"
//Suppose that always the cast is valid("2" can be converted to int 2)
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}