Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If vs overloads vs reflection [closed]

I have a lot of classes with proprties like:

class C1
{
    [PropName("Prop1")]
    public string A {get;set;}

    [PropName("Prop2")]
    public string B {get;set;}

    [PropName("Prop3")]
    public string C {get;set;}
} 

class C2
{
    [PropName("Prop1")]
    public string D {get;set;}

    [PropName("Prop2")]
    public string E {get;set;}

    [PropName("Prop3")]
    public string F {get;set;}
} 

The attribute tells what is the actual property but the name of the C# property doesn't always match. In the case of C1 and C2, C1.A is the same property as C2.D.

These classes are not part of any inheritance chain and I don't have control over them so I cannot change them.

There are some common operations for "Prop1", "Prop2", ... , "PropN". What is the best solution to write these operations without too much code repetition but still make it maintainable.

Solution #1 (if statements - lots of them)

void OperationWithProp1(object o)
{
    string prop1;        

    C1 class1 = o as C1;
    if (class1 != null)
        prop1 = class1.A;

    C2 class2 = o as C2;
    if (class2 != null)
        prop1 = class2.D;

    // Do something with prop1
}

Solution #2 (overloads - lots of them)

void OperationWithProp1(string prop1)
{
    // Do something with prop1
}

void RunOperationWithProp1(C1 class1)
{
    OperationWithProp1(class1.A);
}

void RunOperationWithProp1(C2 class2)
{
    OperationWithProp1(class2.D);
}

Solution #3 (Reflection) - I'm worried about perf because each of these operations will be called thousands of times and there a few hundred operations

void OperationWithProp1(object o)
{
     // Pseudo code:
     // Get all properties from o that have the PropName attribute
     // Look if any attribute matches "Prop1"
     // Get the value of the property that matches
     // Do something with the value of the property
}

Which solution would you pick and why? Do you have other patterns in mind?


EDIT for clarifications:

A lot of classes means tens of them

A lot of properties means 30-40 properties/class

like image 517
Dave Dave Avatar asked Apr 20 '26 11:04

Dave Dave


2 Answers

You can make a wrapper class exposing the properties that you need, and wrapping instances of the actual C1 and C2 classes. One way of doing it would be through delegates:

interface WithProperties {
   string A {get;set;}
   string B {get;set;}
   string C {get;set;}
}
class WrappedCX<T> : WithProperties {
    private readonly T wrapped;
    private readonly Func<T,string> getA;
    private readonly Action<T,string> setA;
    private readonly Func<T,string> getB;
    private readonly Action<T,string> setB;
    private readonly Func<T,string> getC;
    private readonly Action<T,string> setC;
    public WrappedCX(T obj, Func<T,string> getA, Action<T,string> setA, Func<T,string> getB, Action<T,string> setB, Func<T,string> getC, Action<T,string> setC) {
        wrapped = obj;
        this.getA = getA;
        this.setA = setA;
        this.getB = getB;
        this.setB = setB;
        this.getC = getC;
        this.setC = setC;
    }
    public string A {
        get {return getA(wrapped);}
        set {setA(wrapped, value);}
    }
    public string B {
        get {return getB(wrapped);}
        set {setB(wrapped, value);}
    }
    public string C {
        get {return getC(wrapped);}
        set {setC(wrapped, value);}
    }
}

Now you can do something like this:

C1 c1 = new C1();
C2 c2 = new C2();
WithProperties w1 = new WrappedCX(c1, c => c.A, (c,v) => {c.A=v;}, c => c.B, (c,v) => {c.B=v;}, c => c.C, (c,v) => {c.C=v;});
WithProperties w2 = new WrappedCX(c2, c => c.D, (c,v) => {c.D=v;}, c => c.E, (c,v) => {c.E=v;}, c => c.F, (c,v) => {c.F=v;});

At this point, w1 and w2 are both implementing the common WithProperties interface, so you can use them without checking their type.

To get fancy, replace the seven-argument constructor with a constructor that takes a single obj parameter, obtain its class via reflection, check its properties for the custom attributes that you defined, and create/compile LINQ expressions corresponding to the getters and the setters of the properties A, B, and C. This would let you construct your WrappedCX without the ugly lambdas trailing in the call. The tradeoff here is that now the lambdas would be constructed at run time, so would-be compile errors on missing properties would become run-time exceptions.

like image 80
Sergey Kalinichenko Avatar answered Apr 23 '26 01:04

Sergey Kalinichenko


You could dynamically generate proxy classes that access the correct members using the attributed "PropName" names. You'd also want to detect if the properties actually implement get/set before generating calls to them. Also maybe a more sophisticated method to guarantee unique type names for the generated proxies...

See Main() for usage, and below main is an implementation of your OperationWithProp1()

(Here comes a lot of code)

public interface IC
{
    string Prop1 { get; set; }
    string Prop2 { get; set; }
    string Prop3 { get; set; }
}

public class C1
{
    [PropName("Prop1")]
    public string A { get; set; }

    [PropName("Prop2")]
    public string B { get; set; }

    [PropName("Prop3")]
    public string C { get; set; }
}

public class C2
{
    [PropName("Prop1")]
    public string D { get; set; }

    [PropName("Prop2")]
    public string E { get; set; }

    [PropName("Prop3")]
    public string F { get; set; }
}

public class ProxyBuilder
{
    private static readonly Dictionary<Tuple<Type, Type>, Type> _proxyClasses = new Dictionary<Tuple<Type, Type>, Type>();

    private static readonly AssemblyName _assemblyName = new AssemblyName("ProxyBuilderClasses");
    private static readonly AssemblyBuilder _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);
    private static readonly ModuleBuilder _moduleBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name, _assemblyName.Name + ".dll");

    public static void SaveProxyAssembly()
    {
        _assemblyBuilder.Save(_assemblyName.Name + ".dll");
    }

    public static Type GetProxyTypeForBackingType(Type proxyInterface, Type backingType)
    {
        var key = Tuple.Create(proxyInterface, backingType);

        Type returnType;
        if (_proxyClasses.TryGetValue(key, out returnType))
            return returnType;

        var typeBuilder = _moduleBuilder.DefineType(
            "ProxyClassProxies." + "Proxy_" + proxyInterface.Name + "_To_" + backingType.Name,
            TypeAttributes.Public | TypeAttributes.Sealed,
            typeof (Object),
            new[]
            {
                proxyInterface
            });

        //build backing object field
        var backingObjectField = typeBuilder.DefineField("_backingObject", backingType, FieldAttributes.Private);

        //build constructor
        var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] {backingType});
        var ctorIL = ctor.GetILGenerator();
        ctorIL.Emit(OpCodes.Ldarg_0);
        var ctorInfo = typeof (Object).GetConstructor(types: Type.EmptyTypes);
        ctorIL.Emit(OpCodes.Call, ctorInfo);
        ctorIL.Emit(OpCodes.Ldarg_0);
        ctorIL.Emit(OpCodes.Ldarg_1);
        ctorIL.Emit(OpCodes.Stfld, backingObjectField);
        ctorIL.Emit(OpCodes.Ret);

        foreach (var targetPropertyInfo in backingType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            var propertyName = targetPropertyInfo.Name;
            var attributes = targetPropertyInfo.GetCustomAttributes(typeof (PropName), true);

            if (attributes.Length > 0 && attributes[0] != null)
                propertyName = (attributes[0] as PropName).Name;

            var propBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, targetPropertyInfo.PropertyType, null);

            const MethodAttributes getSetAttrs =
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual;

            //build get method
            var getBuilder = typeBuilder.DefineMethod(
                "get_" + propertyName,
                getSetAttrs,
                targetPropertyInfo.PropertyType,
                Type.EmptyTypes);

            var getIL = getBuilder.GetILGenerator();
            getIL.Emit(OpCodes.Ldarg_0);
            getIL.Emit(OpCodes.Ldfld, backingObjectField);
            getIL.EmitCall(OpCodes.Callvirt, targetPropertyInfo.GetGetMethod(), Type.EmptyTypes);
            getIL.Emit(OpCodes.Ret);
            propBuilder.SetGetMethod(getBuilder);

            //build set method
            var setBuilder = typeBuilder.DefineMethod(
                "set_" + propertyName,
                getSetAttrs,
                null,
                new[] {targetPropertyInfo.PropertyType});

            var setIL = setBuilder.GetILGenerator();
            setIL.Emit(OpCodes.Ldarg_0);
            setIL.Emit(OpCodes.Ldfld, backingObjectField);
            setIL.Emit(OpCodes.Ldarg_1);
            setIL.EmitCall(OpCodes.Callvirt, targetPropertyInfo.GetSetMethod(), new[] {targetPropertyInfo.PropertyType});
            setIL.Emit(OpCodes.Ret);
            propBuilder.SetSetMethod(setBuilder);
        }
        returnType = typeBuilder.CreateType();
        _proxyClasses.Add(key, returnType);
        return returnType;
    }

    public static TIProxy CreateProxyObject<TIProxy>(object backingObject, out TIProxy outProxy) where TIProxy : class
    {
        var t = GetProxyTypeForBackingType(typeof (TIProxy), backingObject.GetType());
        outProxy = Activator.CreateInstance(t, backingObject) as TIProxy;
        return outProxy;
    }


    private static void Main(string[] args)
    {
        var c1 = new C1();
        IC c1Proxy;
        CreateProxyObject(c1, out c1Proxy);
        var c2 = new C2();
        IC c2Proxy;
        CreateProxyObject(c2, out c2Proxy);

        c1Proxy.Prop1 = "c1Prop1Value";
        Debug.Assert(c1.A.Equals("c1Prop1Value"));

        c2Proxy.Prop1 = "c2Prop1Value";
        Debug.Assert(c2.D.Equals("c2Prop1Value"));

        //so you can check it out in reflector
        SaveProxyAssembly();
    }

    private static void OperationWithProp1(object o)
    {
        IC proxy;
        CreateProxyObject(o, out proxy);

        string prop1 = proxy.Prop1;

        // Do something with prop1
    }
like image 29
Wes Cumberland Avatar answered Apr 23 '26 01:04

Wes Cumberland