C# 接口和铸造列表
为什么这不起作用,如何修复C# 接口和铸造列表,c#,C#,为什么这不起作用,如何修复 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
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();
无法从type
System.Collections.Generic.List
转换到Interface我想您的问题是Results.ToList()
调用?它将失败,因为ITheInterface
不支持ToList()
。您正在对LINQ查询调用SingleOrDefault()
,该查询将为您提供单个项。对单个项目调用ToList()
没有意义
相反,如果您的代码如下所示:
IEnumerable<SomeObject> Results = from x in dc.Objects
select new SomeObject{... };
结果是一个单一的对象;ToList()仅适用于可枚举项 您需要编写
返回新列表{Results}
(使用集合初始值设定项)或放弃对SingleOrDefault
的调用,并将结果声明为IEnumerable
如果您只需要一个对象,为什么要返回列表?除了其他答案之外,在实现接口时,必须将成员函数声明为
public
:
public class SomeObject: ITheInterface
{
public string a{get;set;}
public string b{get;set;}
...
}
你想说什么
SomeGroup result = results.SingleOrDefault()
return result;
这是因为方法的返回类型是
SomeGroup
(我推断)为什么什么不起作用?您得到的是什么错误?请给出一个简短但完整的程序,否则我们无法判断出发生了什么错误。您声明返回的函数是什么?如果它返回一个SomeGroup,则放弃对ToList的调用。
SomeGroup result = results.SingleOrDefault()
return result;