jeudi 21 juillet 2016

Implement Same Function for different Generic Types with Reflection

I'm currently working on a Solution to compare two elemts of the same object with eachother. Code looks like this:

public double Compare(Data o)
    {
        double same = 0;
        double different = -1;

        foreach (var prop in o.GetType().GetProperties())
        {
            if (prop.GetValue(o) == prop.GetValue(this))
                same++;
            else
                different++;
        }            
        return (same / (different + same)) * 100;
    }

Data is an example for an implementation of the IData Interface, created by my own. Since there are more types of different datastructures, there are identical implementations of the function in each and every object, that implements the particular interface. Now, this kinda disturbes me because it seems to be stupid to have the exact same lines of code in different classes.

Is there any chance, that I can use one method for all of my different classes and still work with reflection? I thought about the szenario quite a while and just couldn't figure out how to refere to the correct "this" reference. Only idea I got is, to write an helper class with two parameters for the function and call that helper method in the specific data call implementation. Code would look like this:

class CompareHelper
{
     public double Compare(Data o, Data callingObject)
     {
        double same = 0;
        double different = -1;

        foreach (var prop in o.GetType().GetProperties())
        {
            if (prop.GetValue(o) == prop.GetValue(callingObject))
                same++;
            else
                different++;
        }  
        return (same / (different + same)) * 100;
     }
 }

Any other recommendations?

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire