Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 返回IEnumerable<;IMyInterface>;韩元';t工作-必须使用IEnumerable<;MyObj>;相反_C#_.net - Fatal编程技术网

C# 返回IEnumerable<;IMyInterface>;韩元';t工作-必须使用IEnumerable<;MyObj>;相反

C# 返回IEnumerable<;IMyInterface>;韩元';t工作-必须使用IEnumerable<;MyObj>;相反,c#,.net,C#,.net,我正在尝试返回IEnumerable。我有一个从函数返回的类,MyClass:IMyInterface IEnumerable<IMyInterface> test() { tmpList = new List<MyClass>(); tmp1 = new MyClass(); tmp2 = new MyClass(); tmpList.Add(tmp1); tmpList.Add(tmp2); return tmpList

我正在尝试返回
IEnumerable
。我有一个从函数返回的类,
MyClass:IMyInterface

IEnumerable<IMyInterface> test() {
    tmpList = new List<MyClass>();
    tmp1 = new MyClass();
    tmp2 = new MyClass();
    tmpList.Add(tmp1);
    tmpList.Add(tmp2);
    return tmpList;
}
IEnumerable测试(){
tmpList=新列表();
tmp1=新的MyClass();
tmp2=新的MyClass();
tmpList.Add(tmp1);
tmpList.Add(tmp2);
返回tmpList;
}

编译器将不允许,这对我来说很奇怪,因为MyClass:MyInterface。编译器给出了如下错误:
“无法将类型System.Collections.Generic.IEnumerable隐式转换为System.Collections.Generic.IEnumerable使用
产生返回
,而不仅仅是
返回
。这将把一个简单的对象变成对象的枚举

IEnumerable<IMyInterface> test() {
    yield return new MyClass();
    yield return new MyClass();
    yield return new MyClass();
}
您应该这样做:

IEnumerable<IMyInterface> test() {
    tmpList = new List<IMyInterface>();  // this is the important bit
    tmp1 = new MyClass();
    tmp2 = new MyClass();
    tmpList.Add(tmp1);
    tmpList.Add(tmp2);
    return tmpList;
}
return tmpList.Cast<IMyInterface>(); // requires using System.Linq in usings
IEnumerable测试(){
tmpList=new List();//这是重要的一位
tmp1=新的MyClass();
tmp2=新的MyClass();
tmpList.Add(tmp1);
tmpList.Add(tmp2);
返回tmpList;
}
或者,您可以这样做:

IEnumerable<IMyInterface> test() {
    tmpList = new List<IMyInterface>();  // this is the important bit
    tmp1 = new MyClass();
    tmp2 = new MyClass();
    tmpList.Add(tmp1);
    tmpList.Add(tmp2);
    return tmpList;
}
return tmpList.Cast<IMyInterface>(); // requires using System.Linq in usings
返回tmpList.Cast();//需要在使用中使用System.Linq

MyClass是一个
IMyInterface
,它与
IEnumerable
不同。你想完成什么?一个只包含一个物体的东西。这就是OP想要的吗?不知道他想要什么。添加了一个不带
IEnumerable
的示例。还需要指出的是,在访问枚举之前,函数实际上不会运行。有点得寸进尺,得寸进尺还是优势!通常,延迟执行是有用的。如果过早地中断foreach循环(例如,因为找到了所需的项),则枚举器的其余部分将根本不会执行。这可以为长时间枚举节省宝贵的资源。枚举可能是无止境的。想象一个计算并返回素数的例子。哦,明白了,这是一个优势!这基本上使LINQ工作,对吗?任何用fluent模式实现的东西……这是一个很好的建议。我故意举了一个微不足道的例子。在我的“真实”代码中,我使用了一个工厂模式,它允许我生成列表,其中T必须是一个新的对象(而不是接口)。所以我和演员们一起去了——作品很美!