简体   繁体   中英

C# Generics - How to use type

I am fairly new to C# generics and am wondering how a few things work.

If I have this:

public class Foo<T>

On my class I have a method GetType, which will simply return the type of T. How would I do that so my method would de able to work with T.

public string GetType();
{
    return T.GetType().ToString();
}

I'm trying to learn a simple example to help me understand.

Thanks.

public string GetTypeName()
{
    return typeof(T).ToString();
}

T is not an instance of something, it is actual type parameter . Similarly you can't say String.GetType() , but you can say typeof(String) . In general, you call GetType() on instances and typeof(something) on types.

Also I've renamed your GetType method into GetTypeName because method GetType is declared on object type and thus compiler would complain if you try to use it.

And yet one thing: semicolon is illegal before method body, so I removed it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM