In Java , I can simply have class names like this:
public class MyClass
{
public static String toString(Class<?> classType)
{
return classType.getName() ;
}
}
package this.that;
public class OneClass
{
}
public static void main()
{
System.out.println(MyClass.toString(OneClass));
}
to return me full class name "this.that.OneClass".
I tried same in C# , but got error that i'm using OneClass as type.
public class MyClass
{
public static String ToString(Type classType)
{
return classType.Name ;
}
}
namespace this.that
{
public class OneClass
{
}
}
static Main()
{
Console.WriteLine(MyClass.ToString(OneClass)); // expecting "this.that.OneClass" result
}
Note that I don't want to use class instance
First, let's fix your Java code: this call
System.out.println(MyClass.toString(OneClass));
would not compile unless you add .class
to OneClass
:
System.out.println(MyClass.toString(OneClass.class));
The equivalent construct to .class
syntax in C# is typeof
. It takes a type name, and produces the corresponding System.Type
object:
Console.WriteLine(MyClass.ToString(typeof(OneClass)));
In addition, C# does not allow this
as an identifier * , so you should rename the namespace to exclude the keyword. Finally, Name
will print the unqualified name of the class. If you would like to see the name with the namespace, use FullName
property:
public static String ToString(Type classType) {
return classType.FullName;
}
* The language allows you to use this
if you prefix it with @
, but one should make every effort to avoid using this trick.
The line:
Console.WriteLine(MyClass.ToString(OneClass));
isn't valid C#
. You need to do:
Console.WriteLine(MyClass.ToString(typeof(OneClass)));
You need to use namespaces instead of packages in c#
public class MyClass
{
public static String toString(Type classType)
{
// returns the full name of the class including namespace
return classType.FullName;
}
}
you can use namespace to package classes
namespace outerscope.innerscope
{
public class OneClass
{
}
}
To print the full name
Console.WriteLine(MyClass.toString(typeof(outerscope.innerscope.OneClass)));
In C# you of course must use typeof(OneClass) as others suggested.
But your toString method is also wrong, you have to use Type.FullName to get namespace, not just Type.Name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.