如何进行安全的类型转换

本文介绍了一种使用反射机制进行属性绑定的方法,并讨论了在不同属性类型之间进行安全类型转换的技术细节。通过示例代码展示了如何利用Binding类来实现属性绑定,确保不同类型之间的正确转换。
通过反射给控件,或者对象的的属性设计值的时候,会遇到类型的转换问题
如果属性的类型只有几种的情况,只用switch就可以了
但是如果属性类型的情况比较多,那么就得找其它办法了.
Binding类中给我们一个比较安全的办法
object instancevalue;//要给控件绑定的对象的值
Control bindcontrol;
System.Type controltype 
= bindcontrol.GetType();
PropertyInfo[] controlpro 
= controltype.GetProperties();

foreach (PropertyInfo tpi in controlpro)
{
    
if (tpi.Name == controlproperty)//controlproperty指到要绑定到的控件的属性名
    {

        Type controlpropertytype 
= tpi.PropertyType;//这个控件属性要求的类型,
        
//经过类型转换的值
       object convertedprovalue= Convert.ChangeType(instancevalue, controlpropertytype); 

       tpi.SetValue(bindcontrol, convertedprovalue, 
null);


        
//if (tpi.Name == "Text")
        
//    tpi.SetValue(bindcontrol, instancevalue.ToString(), null);
        
//else
        
//    tpi.SetValue(bindcontrol, instancevalue, null);
    }
    
else
        
continue;
}


//这是从Binding的类中反射得来的,如果以上代码没有能完成转换的任务,可以参考以下的代码
   TypeConverter converter = TypeDescriptor.GetConverter(value.GetType());
    
if ((converter != null&& converter.CanConvertTo(propertyType))
    {
        
return converter.ConvertTo(value, propertyType);
    }
    
if (value is IConvertible)
    {
        obj2 
= Convert.ChangeType(value, propertyType);
        
if (obj2.GetType().IsSubclassOf(propertyType) || (obj2.GetType() == propertyType))
        {
            
return obj2;
        }
    }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值