是否可以拥有IEnumerable <t>?</t>的属性

时间:2010-09-02 18:54:03

标签: c# .net collections ienumerable

我有一个IEnumerable<T>的课程,我想要有不同的属性,提供过滤的IEnumerable<T>访问权限。

例如:

class Shape
   ShapeType = Box/Sphere/Pyramid

class ShapeCollection : IEnumerable<Shape>
{
   public IEnumerable<Shape> OnlyBox
   {
       foreach(var s in this)
       {
           if (s.ShapeType == Box)
               yield return s;
       }
   }
}

这是怎么回事?只是不确定,完全是这样。

感谢。

7 个答案:

答案 0 :(得分:11)

当然可以,但您可能希望将其重写为

public IEnumerable<Shape> OnlyBox
{
    get { return this.Where(x => x.ShapeType == ShapeType.Box); }
}

完全相同。

答案 1 :(得分:4)

class ShapeCollection : IEnumerable<Shape>
{
   public IEnumerable<Shape> OnlyBoxes
   {
       get { return this.Where(s => s.ShapeType == Box); }
   }
}

您错过了get /括号以使其成为一种方法。另外什么是Box,你的意思是ShapeType.Box?也可以将其重命名为OnlyBoxes,似乎更具描述性。

答案 2 :(得分:2)

当然,即使@mquander的解决方案可能更优雅,这应该可行(据我所见)。

答案 3 :(得分:1)

这是有效的,但我认为是多余的。如果要公开强类型的形状列表:

public class Shape
{

}

public class SomethingThatHasShapes
{
   public List<Shape> Shapes { get; set; }
   public Boxes
   {
      get { return Shapes.Where(s => s.ShapeType = ShapeType.Box); }
   }  


}

List<T>类实现IEnumerable。

答案 4 :(得分:1)

就个人而言,我认为您的OnlyBox财产是多余的。因为您的类的用户将始终可以选择使用具有相同性能的Linq。因此,除非你能比Linq方法做得更好,我认为将它留给类的用户是很好的,如:

var filtered = shapeCol.Where(s => s.ShapeType == Box);

但如果你想要一个房产,而不是:

foreach(var s in this)
{
    if (s.ShapeType == Box)
        yield return s;
}
你可以写:

return this.Where(s => s.ShapeType == Box);

答案 5 :(得分:1)

更像LINQ的时尚会为你的收藏提供一种方法:

public IEnumerable<Shape> Boxes()
{
    return this.Where(ss => ss.ShapeType == ShapeType.Box);
}

或者只是让用户执行Where子句:

// gather boxes
var query = from shape in shapes
            where shape.ShapeType == ShapeType.Box
            select shape;

否则,IEnumerable作为属性没有任何问题(记住属性应该如此简单,他们很少抛出异常)。

答案 6 :(得分:0)

是的。你有什么是好的。你可以转换为基于lambda的,如果你更喜欢它的表现力,虽然lambda版本有时性能较差(不是说我将lambda版本更改为2.0样式,除非它证明有问题,但足够的是我不会将完美的2.0风格改为基于lambda的风格,除非它使很多更具表现力。)

相关问题