【问题标题】:Casting a custom collection using as fails使用 as 强制转换自定义集合失败
【发布时间】:2017-05-24 09:10:24
【问题描述】:

我有一个自定义集合如下:(我不会显示类的所有代码)

public class MyCollection : IList<MyOBject>, ICollection<MyOBject>, IEnumerable<MyOBject>, IEnumerable, IDisposable
{
    //Constructor
    public MyCollection (MyOBject[] shellArray);
    // blah blah
}

我只想要 SomeValue=false 集合中的条目,我正在尝试找出为什么我不能使用 as 运算符,如下所示:

MyCollection SortCollection(MyCollection collection)
{
    MyCollection test1 = collection.Where(x => (bool)x["SomeValue"].Equals(false)) as MyCollection ; //test1 = null

    var test2 = collection.Where(x => (bool)x["SomeValue"].Equals(false)) as MyCollection ;          //test2 = null

    var test3 = collection.Where(x => (bool)x["SomeValue"].Equals(false)); //test3 is non null and can be used
    return new MyCollection (test3.ToArray());
}

为什么我不能使用test1test2中的代码

【问题讨论】:

    标签: c# casting icollection


    【解决方案1】:

    我猜你错误地认为MyCollection.Where 的结果是MyCollection。不是,是IEnumerable&lt;T&gt;,其中T是项目类型,在本例中为MyOBject

    这段代码应该可以工作:

    IEnumerable<MyOBject> test1 = collection.Where(x => (bool)x["SomeValue"].Equals(false));
    

    您可能希望将其反馈给您的 MyCollection 构造函数:

    MyCollection coll = new MyCollection(test1.ToArray());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      相关资源
      最近更新 更多