C# 返回一个通用的 IEnumerable<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11441395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:52:11  来源:igfitidea点击:

returning a generic IEnumerable<T>

c#genericsienumerable

提问by Thousand

I'm messing around with generics and IEnumerable abit, but i'm kindof stuck. Here's what i'm trying to do: I want to have a method that returns any collection type - that implements IEnumerable (?) - (so e.g: List, Stack, Queue, ...)

我正在使用泛型和 IEnumerable abit,但我有点卡住了。这就是我想要做的:我想要一个返回任何集合类型的方法 - 实现 IEnumerable (?) - (例如:列表、堆栈、队列等)

furthermore, i want to be able to return any collection type, of any datatype. so i want this method to be able to return a List<string>,as well as a Stack<int>, as well as a List<double>... etc etc.

此外,我希望能够返回任何数据类型的任何集合类型。所以我希望这个方法能够返回 aList<string>,和 a Stack<int>,以及 a List<double>... 等等。

 public IEnumerable<T> returnSomething() 
    {
        Stack<int> stackOfInts = new Stack<int>();
        List<string> listOfStrings = new List<string>();
        return stackOfInts;
    }

this is what i've tried so far. this however doesn't work, i get this error:

这是我迄今为止尝试过的。但是这不起作用,我收到此错误:

Cannot implicitly convert type 'System.Collections.Generic.Stack<int>' to 'System.Collections.Generic.IEnumerable<T>'. An explicit conversion exists (are you missing a cast?)

however, if i replace the IEnumerable<T>in the method signature to IEnumerable<int>, i can return any collection of type int. This however means, that now i can't return the ListOfStringsanymore.

但是,如果我将IEnumerable<T>方法签名中的替换为,则IEnumerable<int>可以返回任何 int 类型的集合。然而,这意味着,现在我不能再返回ListOfStrings了。

would appreciate any suggestions or ideas :)

将不胜感激任何建议或想法:)

采纳答案by Mark Byers

You need to add a generic type parameterto your method:

您需要为您的方法添加一个泛型类型参数

public IEnumerable<T> ReturnSomething<T>() 
{
    Stack<T> stackOfT = new Stack<T>();
    return stackOfT;
}

The type parameter appears after the method name, but before the parameters. It is also possible to have a method with more than one type parameter.

类型参数出现在方法名称之后,但在参数之前。一个方法也可以有多个类型参数。

When you call the method you can specify the type:

当您调用该方法时,您可以指定类型:

IEnumerable<int> myInts = ReturnSomething<int>();

回答by oleksii

The trick is to declare<T>right, if you define generic <T>, then you have to stick to it in your methods, so if you have IEnumerable<T>then elsewhere in your method you must use <T>and not <int>or any other type.

诀窍是声明<T>正确,如果你定义了 generic <T>,那么你必须在你的方法中坚持它,所以如果你IEnumerable<T>在你的方法中的其他地方有那么你必须使用<T>而不是<int>或任何其他类型。

It is only latter when you actually useyou generic type you substitute generic <T>for a real type.

只有在您实际使用泛型类型时才泛型替换<T>为真实类型。

See a sample

查看样本

class Foo<T>
{
    public IEnumerable<T> GetList()
    {
        return new List<T>();
    }

    public IEnumerable<T> GetStack()
    {
        return new Stack<T>();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Foo<int> foo = new Foo<int>();
        IEnumerable<int> list = foo.GetList();
        IEnumerable<int> stack = foo.GetStack();

        Foo<string> foo1 = new Foo<string>();
        IEnumerable<string> list1 = foo1.GetList();
        IEnumerable<string> stack1 = foo1.GetStack();
    }
}

回答by HatSoft

Yes you can return any type if you change IEnumerable<T> to IEnumerable<dynamic>

是的,如果您更改 I,您可以返回任何类型Enumerable<T> to IEnumerable<dynamic>

like this:

像这样:

public IEnumerable<dynamic> returnSomething() 
{
.....

回答by burning_LEGION

public IEnumerable<T> returnSomething() 
{
    Stack<int> stackOfInts = new Stack<int>();
    return (IEnumerable<T>) stackOfInts;
}

回答by Joe

The type parameter needs to be specified by the caller somewhere.

类型参数需要由调用者在某处指定。

Either when instantiating a generic class:

在实例化泛型类时:

public class MyClass<T>
{
    public IEnumerable<T> returnSomething()
    {
        Stack<T> stackOfTs = new Stack<T>();
        List<T> listOfTs = new List<T>();
        return stackOfTs;
    }
}

var v = new MyClass<int>();
foreach(var item in v.returnSomething())
{
}

Or when calling a generic method of a non-generic class:

或者在调用非泛型类的泛型方法时:

public class MyClass
{
    public IEnumerable<T> returnSomething<T>()
    {
        Stack<T> stackOfTs = new Stack<T>();
        List<T> listOfTs = new List<T>();
        return stackOfTs;
    } 
}


var v = new MyClass();
foreach(var item in v.returnSomething<int>())
{
}

回答by sarder kamruzzaman polash

For more help full structure given below ...

如需更多帮助,请参阅下面给出的完整结构...

my model is

我的模型是

  public class Student
{
    public int studentId { get; set; }
    public string studentName { get; set; }
    public string subject { get; set; }
    public string studentClass { get; set; }
    public int RollNumber { get; set; }

}

IEnumerable return datalist

IEnumerable 返回数据列表

 public static IEnumerable<Student> ReturnSomething()
        {
            IList<Student> studentList = new List<Student>()
            {
                new Student()
                    {studentId = 1, studentName = "Bill", subject = "Science", studentClass = "nine", RollNumber = 01},
                new Student()
                    {studentId = 2, studentName = "Steve", subject = "Arts", studentClass = "ten", RollNumber = 03},
                new Student()
                    {studentId = 3, studentName = "Ram", subject = "Commerce", studentClass = "nine", RollNumber = 05},
                new Student()
                    {studentId = 1, studentName = "Moin", subject = "Science", studentClass = "ten", RollNumber = 06}
            };

            return studentList;
        }

and last one is access code

最后一个是访问代码

 Student student = new Student();
 IEnumerable<Student> studentList = ReturnSomething();

        foreach (Student VARIABLE in studentList)
        {
            student.studentName += VARIABLE.studentName + " "+ "Class= ";
            student.studentClass += VARIABLE.studentClass + " ";
        }

        Console.WriteLine(student.studentName + student.studentClass);
        Console.ReadKey();