【发布时间】: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