Equivalent in C # ClassT of java

2

In Java, I can declare a generic T and that a method receives as an argument the class to which the generic belongs. For example:

protected static <T> T hacerAccion (Class<T> respuesta) {
    //implementación...
}

What would be the equivalent code in C # for this method, mainly for the Class<T> respuesta argument?

    
asked by paco 11.05.2017 в 23:15
source

3 answers

1

To define a generic method in c # would be:

protected static T hacerAccion <T>(Class<T> respuesta) { //implementación... }

Obviously the class Class would have to define it.

    
answered by 12.05.2017 в 17:11
0

Look, from what I understand, you want some way to get what java gives you, this is a very open example that might be useful for you. There are many paths to it, this is one of them.

public X metodoquedevuelve<X>(X valor)
{
    Type x = typeof(X); 
    if (Valor si es algún tipo) { } 
    return (X)someObject; 
}
    
answered by 12.05.2017 в 17:11
0

Taking this code in Java:

protected static <T> T hacerAccion (Class<T> respuesta) {
    //implementación...
}

It could be possible to call it this way:

Integer i = hacerAccion(Integer.class);

If what you want is that, what you should do in C # is the following:

protected static T hacerAccion<T> () {
    //implementación...
}

Maybe you want Class<T> to do verifications. In that case, what you want is typeof(T) :

protected static T hacerAccion<T> () {
    if (typeof(T) == typeof(int))
    {
        // ...
    }
    //implementación...
}

Unlike Java, in C # you can know the type of data at runtime without having to pass an object that represents it. If you still want an object that represents a type, it would be System.Type , however there is no System.Type<T> , use typeof(T) (which returns System.Type ) instead. Thanks this C # does not need Class<T> and does not have it.

    
answered by 21.05.2017 в 14:41