2013-07-02 19 views
1
public IEnumerable<decimal> SomeKeys 
{ 
    get 
    { 
     return dbContext.SomeTable.Select(x=>x.Key); 
    } 
} 

public IEnumerable<decimal> SomeOtherKeys 
{ 
    get 
    { 
     var ret = IEnumerable<decimal>(); // interface name is not 
              // valid as this point 
     // do stuff with ret 
     return ret; 
    } 
} 

用我目前的代码,我得到上面的例外。我需要退回List<decimal>吗?或者我该如何返回IEnumerableIQueriable数据类型?“接口名称在这一点上是无效的”

+0

它们接口,而不是真正的“数据类型”。我认为关于接口的基本教程将会使这个问题变得清晰:c –

回答

7

这是var ret = IEnumerable<decimal>();只是无效C#代码,也就是说。

您可能需要做这样的事情:

var ret = new List<decimal>(); 

Remeber是List,引用文档,从IEnumerable<T>派生了。

public class List<T> : IList<T>, ICollection<T>, 
    IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, 
    IEnumerable 

所以像

public IEnumerable<decimal> SomeOtherKeys 
{ 
    get 
    { 
     var ret = new List<decimal>();           
     // do stuff with ret 
     return ret; 
    } 
} 

的代码是完全有效的。

1

在您的SomeOtherKeys属性获取器中,您必须实例化一个实现了IEnumerable<decimal>接口的类。

更改为List<decimal>会很好。

var ret = new List<decimal>(); 
ret.Add(1.0M); 
ret.Add(2.0M); 
1

您创建类实例,但从来没有接口,因为它们只是代码合同,但不能实例化。

你必须选择适合你的场景的实施IEnumerable<T>的集合,并坚持下去。

你的财产SomeOtherKeys能保持签名,没有必要去改变它作为使用接口作为返回值是完全有效和良好的实践有助于降低耦合