【问题标题】:How can I keep catching exceptions, in a way that would allow me to resume whatever I'm doing?我怎样才能继续捕获异常,以使我能够继续我正在做的事情?
【发布时间】:2014-02-13 08:30:53
【问题描述】:

抱歉,如果标题不够清楚。但基本上我有一个通过反射复制Components 的方法。

public static T GetCopyOf<T>(this Component comp, T other) where T : Component
{
    Type type = comp.GetType();
    if (type != other.GetType()) return null; // type mis-match
    BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default;
    PropertyInfo[] pinfos = type.GetProperties(flags);
    foreach (var pinfo in pinfos) {
        if (pinfo.CanWrite)
            pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
    }
    FieldInfo[] finfos = type.GetFields(flags);
    foreach (var finfo in finfos) {
        finfo.SetValue(comp, finfo.GetValue(other));
    }
    return comp as T;
}

像这样使用它:comp1 = comp1.GetCopyOf(comp2);

工作舒适。

但是,在某些情况下,属性的 setter(CanWrite 为真)但 setter 抛出异常,例如:

public virtual Texture mainTexture
{
    get
    {
        Material mat = material;
        return (mat != null) ? mat.mainTexture : null;
    }
    set
    {
        throw new System.NotImplementedException(GetType() + " has no mainTexture setter");
    }
}

在这种情况下,如果我得到这个异常,我想做的就是继续下一个属性(即忽略当前属性 - 不要中断)

那么我怎样才能捕捉到这个异常,让我可以继续复制其他属性呢?我想它必须是一个递归方法,因为可能有其他属性会在它们的 setter 中引发异常。

表达我想要的另一种方式是if (there's an exception) continue;

谢谢。

【问题讨论】:

    标签: c# exception reflection properties exception-handling


    【解决方案1】:

    抱歉,由于某种原因我没有想到这一点:

        if (pinfo.CanWrite) {
            try {
                pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
            }
            catch { }
        }
    

    【讨论】:

      【解决方案2】:

      如下吞下异常:

      if (pinfo.CanWrite)
      {
          try
          {
              pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
          }
          catch(System.NotImplementedException ex)
          { 
              //do nothing
          }
      }
      

      【讨论】:

      • 谢谢。问完之后,我立马想到要这么做。出于某种原因...
      • 嗯,我不知道为什么,但出于某种原因,这样做似乎并没有真正抓住它 - 它仍然会中断。我必须像catch { } 那样做,知道为什么吗?
      • 可能是其他类型的异常(other than System.NotImplementedException)被抛出;在这种情况下,catch {} 将起作用
      • 我不这么认为。因为在控制台中我仍然输出NotImplementedException 已被抛出。
      猜你喜欢
      • 2012-02-27
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      • 2012-01-12
      • 2022-07-25
      相关资源
      最近更新 更多