抱歉,标题不够清楚。但基本上我有一种Component
通过反射复制s的方法。
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
是true),但该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;
谢谢。
抱歉,出于某些原因,我没有想到这一点:
if (pinfo.CanWrite) {
try {
pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
}
catch { }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句