开发者

C# Generics - How to use type

开发者 https://www.devze.com 2023-03-22 10:49 出处:网络
I am fairly new to C# generics and am wondering how a few things wo开发者_如何学运维rk. If I have this:

I am fairly new to C# generics and am wondering how a few things wo开发者_如何学运维rk.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消