2009-06-02 95 views
0

为什么没有这个工作,以及如何解决?接口和铸造列表

public interface ITheInterface 
{ 

    string a{get;set;} 
    string b{get;set;} 
} 

public class SomeObject: ITheInterface 
{ 
    string a{get;set;} 
    string b{get;set;} 
    ... 
} 

public class SomeGroup 
{ 
    ITheInterface Result; 
    ... 
} 

var results= from y in dc.Groups 
       where y.id==1 
       select new SomeGroup 
         { 
         Result= (from x in dc.Objects 
         select new SomeObject{... } 
         ).SingleOrDefault(), 
         } 

return results.ToList(); 

无法从System.Collections.Generic.List类型转换为界面

+1

为什么没有工作?你遇到了什么错误? – 2009-06-02 00:34:01

+0

请给出一个简短的*完整的*程序,否则我们不能告诉发生了什么问题。 – 2009-06-02 05:32:31

回答

1

我认为你的问题是与Results.ToList()电话吗?它会失败,因为ITheInterface不支持ToList()。您正在LINQ查询上调用SingleOrDefault(),该查询为您提供单个项目。在单个项目上调用ToList()没有任何意义。

相反,如果你的代码这样写的:

IEnumerable<SomeObject> Results = from x in dc.Objects 
            select new SomeObject{... }; 

然后,Results.ToList()会给你一个List<SomeObject>

如果您实际寻找的是一个List<ITheInterface>相反,你可以这样做:

Results.Cast<ITheInterface>().ToList() 
0

结果是一个单一的对象; ToList()仅适用于Enumerables。

您需要编写return new List { Results };(这使用集合初始值设定项)或免除对SingleOrDefault的调用并声明结果为IEnumerable<ITheInterface>

如果你只想要一个对象,为什么你要返回一个List?

0

除了其他的答案,当你实现一个接口,您必须public宣布该成员函数:

public class SomeObject: ITheInterface 
{ 
    public string a{get;set;} 
    public string b{get;set;} 
    ... 
} 
0

你想说

SomeGroup result = results.SingleOrDefault() 
return result; 

这是因为返回类型你的方法是SomeGroup(我推断)