Question

Sorry if the title isn't clear enough. But basically I have a method that copies Components via reflection.

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;
}

Use it like: comp1 = comp1.GetCopyOf(comp2);

Works nice and cozy.

However, there are instances where there is a setter to a property (CanWrite is true) but the setter throws an exception, like this for example:

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

In this case, if I get this exception, what I wanna do is to just move on to the next property (i.e. just ignore the current one - don't break)

So how can I catch this exception, in a way that would allow me to resume copying other properties? I guess it has to be a recursive method since there could be other properties that throw an exception in their setter.

Another way to express what I want is if (there's an exception) continue;

Thanks.

Was it helpful?

Solution

Apologies, for some reason I didn't think of this:

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

OTHER TIPS

Swallow the exception as follows:

if (pinfo.CanWrite)
{
    try
    {
        pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
    }
    catch(System.NotImplementedException ex)
    { 
        //do nothing
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top