What is the c# equivalent of Java’s class type?

In Java, it is convenient for class to use the generic parameter X But c#'s type class doesn't have this

So in c#, how do you handle the following java code?

public <X> X methodThatReturns(Class<X> clazz) { ... }

There seems to be no way to connect the return value and the passed type in C #

Clarifying several answers indicates that method parameters are not required because the method can be simply defined as methodthatreturns < x > ()

But if you do have some unknown type variables, there is basically no way to call such a generic method so that it returns an object with type T?

In Java, you can freely pass class < x > variables without losing type information, but it seems that you may encounter restrictions when passing equivalent type variables in c# because you can't use them when you need to call generic methods

Solution

public X methodThatReturns<X>(Class<X> clazz) { ... }
public X methodThatReturns<X>(Class<X> clazz) { ... }

Also remember that there is no type erasure in C #, so you can do something like (T) without worrying. If class is a Java "class" object rather than a "some class" placeholder:

public X methodThatReturns<X>(X value)
{
    Type x = typeof(X); // that's fine
    if (value is SomeType) { } // that's fine too    
    return (X)someObject; // I think you get the point
}

Edit:

Similarly, since the generic type information will not be lost after compilation, you do not need to explicitly pass in the type:

public X methodThatReturns<X>()
{
    Type xType = typeof(X); // Type is to C#/.Net what Class<X> is to Java.
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>