有没有办法测试我的转换,以避免使用例外? [英] Is there any way to test my conversions to avoid using exceptions?

查看:204
本文介绍了有没有办法测试我的转换,以避免使用例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Reflection来构建DataRows中的任意对象,当橡胶终于满足道路时,我需要从DataRow中获取一个值并将其分配给对象的属性。



由于DataRows可以满足不支持转换的类型,其中许多会导致必须处理的异常。例如,DBnulls可能会在DataRow中爬起来,或者某些数字格式不能很好地转换为另一个,等等。有没有办法避免抛出异常? (我不会接受巨大的切换语句检查目标对象属性和源数据中每种类型的组合。)

  public void Merge(DataRow data)
{
PropertyInfo [] props = this.GetType()。GetProperties(BindingFlags ...);
foreach(PropertyInfo pi in props.Where(p => T_IsPrimitive(p.PropertyType)))
{
对象src = null;
if(dataAsDataRow.Table.Columns.Contains(pi.Name))
src =((DataRow)data)[piName];
if(src!= null)
{
if(src.GetType()!= pi.PropertyType){
try {
src = Convert.ChangeType src,pi.PropertyType);
} catch(InvalidCastException e){
try {src = Convert.ChangeType(src.ToString(),pi.PropertyType); }
catch {throw e; }
}
}
pi.SetValue(this,src,null);
}
}
}

public bool T_IsPrimitive(Type t)
{
return t.IsPrimitive || t == typeof(Decimal)|| t == typeof(String)||
t == typeof(DateTime)|| t == typeof(TimeSpan)
}

所以有没有办法在我之前看与 ChangeType 转换一起飞跃?






解决方案



感谢Stecya,这里是我想出的:

  if(src.GetType()!= pi.PropertyType){
object converted = null;
TypeConverter converter = TypeDescriptor.GetConverter(pi.PropertyType);
if(converter!= null){
if(converter.CanConvertFrom(vType))
converted = converter.ConvertFrom(src);
else if(converter.CanConvertFrom(typeof(String)))
converted = converter.ConvertFrom(src.ToString());
}
src =转换;
}
if(src!= null)
pi.SetValue(this,src,null);

逻辑上相当,优雅,没有更多的例外!

解决方案

使用 TypeConverter 检查是否可以在类型之间转换

  bool CanConvert(Type from,Type to)
{
TypeConverter converter = TypeDescriptor.GetConverter(to);
return converter!= null&&& converter.CanConvertFrom(从);
}

此外,您可以使用此TypeConverter实际从一种类型转换为另一种类型p>

I'm constructing arbitrary objects from DataRows using Reflection, and when the rubber finally meets the road, I need to take a value from the DataRow and assign it to the property on the object.

Because DataRows can be full of types that don't support conversion, many of these result in exceptions that have to be handled. For example, DBnulls might creep up in the DataRow, or some numeric format that doesn't nicely convert to another, etc. Is there any way I can avoid throwing exceptions? (I won't accept gigantic switch statements checking for every combination of types in the target object property and source data.)

public void Merge(DataRow data)
{
  PropertyInfo[] props = this.GetType().GetProperties(BindingFlags...);
  foreach (PropertyInfo pi in props.Where(p => T_IsPrimitive(p.PropertyType)))
  {
    object src = null;
    if( dataAsDataRow.Table.Columns.Contains(pi.Name) )
       src = ((DataRow)data)[pi.Name];
    if (src != null)
    {
       if( src.GetType() != pi.PropertyType ) {
        try {
            src = Convert.ChangeType(src, pi.PropertyType);
        } catch(InvalidCastException e) {
            try { src = Convert.ChangeType(src.ToString(), pi.PropertyType); }
            catch { throw e; }
        }
       }
       pi.SetValue(this, src, null);
    }
  }
}

public bool T_IsPrimitive(Type t)
{
   return t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) ||
          t == typeof(DateTime) || t == typeof(TimeSpan)
}

So is there any way to look before I leap with these ChangeType conversions?


SOLUTION

Thanks to Stecya, here's what I've come up with:

     if( src.GetType() != pi.PropertyType ) {
        object converted = null;
        TypeConverter converter = TypeDescriptor.GetConverter(pi.PropertyType);
        if( converter != null ) {
           if( converter.CanConvertFrom(vType) )
              converted = converter.ConvertFrom(src);
           else if( converter.CanConvertFrom(typeof(String)) )
              converted = converter.ConvertFrom(src.ToString());
        }
        src = converted;
     }
     if( src != null )
        pi.SetValue(this, src, null);

Logically equivalent, elegant, and no more exceptions!

解决方案

Use TypeConverter to check if you can convert between types

bool CanConvert(Type from , Type to)
{
    TypeConverter converter = TypeDescriptor.GetConverter(to);
    return converter != null && converter.CanConvertFrom(from);
}

Also you can use this TypeConverter to actually convert from one type to another

这篇关于有没有办法测试我的转换,以避免使用例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆