C#中,反射类型转换的一个问题

2025-03-24 03:07:31
推荐回答(1个)
回答1:

直接转就行了吧 obj as Dictionary
如果是不同类型的转换
PropertyInfo p=你反射获取的属性
object tv=你设置的值
var tvt = tv.GetType();
var pt = p.PropertyType;
if (pt.Equals(tvt))
{ p.SetValue(control, tv, null); }
else if (pt.Equals(typeof(int)))
{
if (tvt.Equals(typeof(string)))
{
int tvv = 0;
int.TryParse((string)tv, out tvv);
p.SetValue(control, tvv, null);//如果属性是int 值是string 转换值到int
}
}
else if (pt.Equals(typeof(double)))
{
if (tvt.Equals(typeof(string)))
{
double tvv = 0;
double.TryParse((string)tv, out tvv);
p.SetValue(control, tvv, null);//如果属性是double 值是string 转换值到double
}
else if (tvt.Equals(typeof(int)))
{
double tvv = (int)tv;
p.SetValue(control, tvv, null);//如果属性是double 值是int 转换值到double
}
}