Generic method for locating a specific value in several types of similar structures

Asked

Viewed 60 times

0

public enum EXEMPLOENUMERADOR1  { blablabla1, blablabla2 }

public enum EXEMPLOENUMERADOR2 { blablabla3, blablabla4, blablabla5}

public enum EXEMPLOENUMERADOR3 { blablabla6, blablabla7, blablabla8, blablabla9 }


public class ClasseExemplo01 {
    public EXEMPLOENUMERADOR1 exEnum;
    public int level = 1;
}

public class ClasseExemplo02 {
    public EXEMPLOENUMERADOR2 exEnum;
    public int level = 1;
}

public class ClasseExemplo03 {
    public EXEMPLOENUMERADOR3 exEnum;
    public int level = 1;
}

With these structures above I am making today specific methods for each in order to locate a specific value within their structure and return me the object itself of the instance of this specific structure, for example:

//Essas variaveis estão no escopo da minha classe que eu to usando o metodo abaixo...
private List<ClasseExemplo01> listinhaGlobal;
private ClasseExemplo01 instanciaDeExemplo01;

private ClasseExemplo01 GetInformation()
    {
        foreach(ClasseExemplo01 item in listinhaGlobal)
        {
            if (item.exEnum.Equals(instanciaDeExemplo01.exEnum))
            {
                return item;
            }
        }
        return null;
    }

This method is too specific, I can’t reuse it for all types of classes and enumerators different.

How can I create a generic method that accesses and compares values from several similar structures?

  • If I understood your question, you have to use a little logic, for example: what do the 3 classes have in common? an integer attribute, i.e.. the "generic" method would process the information it receives per parameter and return this data type.

  • It would be good to put other parts of the code so we can help better. Anyway it’s a very weird code and it doesn’t even look C#.

1 answer

1

That’s probably what you want:

public class Exemplo<T> {
    private List<T> listinhaGlobal;
    private T instanciaDeExemplo;
    private T GetInformation() {
        foreach(var item in listinhaGlobal) {
            if (item.exEnum == instanciaDeExemplo.exEnum)) {
                return item;
            }
        }
        return null;
    }
}

I put in the Github for future reference.

Then it will instantiate for example as

var objeto = new Exemplo<ClasseExemplo01>();

Still this code is very weird and I think it’s not helping much. I doubt I need to do it this way.

It would be nice to read the C nomenclature standard#. I think it comes from C# and it would be good to eliminate her addictions, especially don’t use everything high in names.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.