简体   繁体   中英

Using Generics C#

I'm new to c# and trying to understang generics. 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.

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.

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). 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.

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
    }
}

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