简体   繁体   English

使用泛型C#

[英]Using Generics C#

I'm new to c# and trying to understang generics. 我是C#的新手,正想了解一下泛型。 I try with this simple class: 我尝试这个简单的类:

using System;
using System.Collections.Generic;


    public class Program<T>
    {
        public static void Main()
        {

            List<T> list = new List<T>();

        }
    }

But when I run the code, I get the error: 但是当我运行代码时,出现错误:

Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true. 无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作。

What am I missing? 我想念什么?

As people already mentioned in comments your code won't compile, but your question is about basics of generics (List) and I'll try to answer it. 正如人们已经在注释中提到的那样,您的代码无法编译,但是您的问题是关于泛型(列表)的基础知识,我将尽力回答。

List<T>

means you need to pass a type parameter to "tell" what type of items your list will contain. 意味着您需要传递一个类型参数来“说明”列表将包含的项目类型。 So you can type 所以你可以输入

List<string>

to create a list of strings. 创建一个字符串列表。 Of course, you can use your own classes, like 当然,您可以使用自己的类,例如

List<MyClass>

to create a list of MyClass objects. 创建MyClass对象的列表。

You can not make the class which contains your entry point (the Main() method) generic (which you did by appending <T> to your Program class). 您不能使包含入口点( Main()方法)的类通用(通过将<T>附加到Program类来完成)。 But that's not necessary anyway. 但这不是必须的。 If you want to use generic classes like List<T> , all you have to do is to specify which type you want to use for it's concrete implementation. 如果要使用List<T>类的泛型类,您要做的就是指定要用于其具体实现的类型。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> list = new List<int>(); // List<T>'s generic parameter T was set to int

        list.Add(5); // 5 is of type int
    }
}

This works fine. 这很好。 You can also build your own generic classes, whose type parameters can in turn be used as arguments for other generic types: 您还可以构建自己的泛型类,其泛型参数又可以用作其他泛型类型的参数:

class MyGenericClass<A>
{
    public void Example()
    {
        List<A> list = new List<A>(); // List<T>'s generic parameter T was set to whatever A is

        list.Add(default(A)); // default(A) is some default value of type A
    }
}

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

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