dimanche 30 octobre 2016

Best way to use reflection

My application pays a performance penalty because I'm using reflection, specifically to get attributes for classes and properties.

In order to optimize my application I want to generate a library that is based on the reflection but replacing it at runtime.

Today I use something like:

MyAttribute[] attributes = (MyAttribute[])Attribute.GetCustomAttributes(typeof(CurrentNamespace.MyClass), typeof(MyAttribute));
var x = GetX(attributes);

I can generate a class with the same class name in a different namespace and call it statically.

MyReflectingClassInterface reflectingClass = getClassFromAssembly("ReflectingNamespace.MyClass");
var x = reflectingClass.getX(); // can't be static if I want to use interface.

Or, Maybe the best way is to use one static switch:

static public X getX(Type type){
    if(type == typeof(CurrentNamespace.MyClass))
        return new X(5); // hard coded answer
}





Aucun commentaire:

Enregistrer un commentaire