简体   繁体   English

C#泛型-如何使用类型

[英]C# Generics - How to use type

I am fairly new to C# generics and am wondering how a few things work. 我是C#泛型的新手,我想知道有些事情是如何工作的。

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. 在我的课堂上,我有一个GetType方法,该方法将简单地返回T的类型。我该怎么做,这样我的方法才能使用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 . T不是某物的实例,而是实际的type参数 Similarly you can't say String.GetType() , but you can say typeof(String) . 同样,您不能说String.GetType() ,但可以说typeof(String) In general, you call GetType() on instances and typeof(something) on types. 通常,在实例上调用GetType() ,在类型上调用typeof(something)

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. 另外,我还将GetType方法重命名为GetTypeName因为方法GetTypeobject类型上声明,因此如果尝试使用它,编译器会抱怨。

And yet one thing: semicolon is illegal before method body, so I removed it. 还有一件事:分号在方法主体之前是非法的,因此我将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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