samedi 15 août 2015

Deep scan using reflection - Is there a better way?

I am working on a way to find all properties which have a certain attribute. This needs to work not just on a single class, but recursively within. In the below example (which works), I have a recursive method which is able to do this, but I am not sure if this is the most efficient way of doing it.

In this scenario, I am looking for string properties with an attribute [Localizable] and replacing the string with a localized text.

Any advise to improve the Localize method or indeed the overall approach is appreciated. Thanks in advance!

public class C1 
{   
    [Localizable]   
    public string L1 { get; set; }   

    public C2[] C2Array { get; set; } 
}

public class C2 
{   
    [Localizable]   
    public string L2 { get; set; }      

    public C3 C3 { get; set; }  

    public List<C3> C3List { get; set; } 
}

public class C3 
{   
    [Localizable]   
    public string L3 { get; set; }
}       

public static void Localize(object o, string culture)
{
    var t = o.GetType();
    if (t.IsPrimitive || t == typeof(string))
    {
        return;
    }

    foreach (var property in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
    {
        var pt = property.PropertyType;
        if (pt == typeof(string))
        {
            if (!Attribute.IsDefined(property, typeof(LocalizableAttribute)))
            {
                continue;
            }
            var localizedText = GetLocalizedText(property.GetValue(o, null).ToString(), cultureInfo);
            property.SetValue(o, localizedText, null);
            continue;
        }

        if (pt.IsArray)
        {
            foreach (var el in (object[])value)
            {
                Localize(el, cultureInfo);
            }
        }
        else if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(List<>))
        {
            foreach (var el in (IEnumerable)value)
            {
                Localize(el, cultureInfo);
            }
        }
        else if (pt.IsClass)
        {
            Localize(value, cultureInfo);
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire