How to make this type of signature in C#?

Asked

Viewed 107 times

3

It is possible to apply this signature type in C#?

public class Teste {

    public void ver(Class<? extends Teste> tipo) {

    }
}

Like?

2 answers

2

The block <? extends Teste> limits the type only to classes that inherit from Teste. In C# if this expression would be where T : Teste. This T can be anything, it is just an identifier for the type that will be used by the consumer of the method.

In C# there is nothing like Class<T> of Java. As noted in ramaral response the closest you can get is using Type.

public class Teste
{
    public void ver<T>(T tipo) where T : Teste
    {
        var tipo = typeof(T);
    }
}

You can see more about the constraints of the generics in C# in Constraints on Type Parameters (C# Programming Guide).

2


The closest C# class is the Type class.

Class is a generic class: Class<T>.

The expression <? extends Teste> limits the type to those who inherit Test. The equivalent in C# is where T : Teste.

Thus, in C#, the "equivalent" to this method will be:

public void ver<T>(T objecto) where T : Teste
{
    Type tipo = typeof(T);
    //use tipo como entender
}

As you only need the type it can be simplified to

public void ver<T>() where T : Teste
{
    Type tipo = typeof(T);
    //use tipo como entender
}

Browser other questions tagged

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