foreach跳出来,毫无例外地抛出

时间:2011-12-14 19:51:55

标签: c# generics

这个'foreach'代码将退出工作状态,似乎是由于某些错误。但是,不会抛出任何异常。有什么好理由吗?循环中的代码(即评论所在的位置)永远不会到达。失败就在它枚举的时候。

foreach (DeviceOption<int> d in _deviceOptions.Where(d => d.HasChanges))
{
    //Call some DAL method
}

如果这是等式的一部分,这就是'DeviceOption'类代码:

public class DeviceOption
{
    private object _state;
    public object State
    {
        get { return _state; }
        set
        {
            if (_state == value)
            {
                return;
            }
            HasChanges = true;
            _state = value;
        }
    }
    public bool UserEditable { get; set; }
    public DateTime Timestamp { get; set; }
    public int UserId { get; set; }
    public bool HasChanges { get; set; }
    public bool IsNew { get; set; }
    public Guid ID { get; set; }
    public string DisplayCategory { get; set; }
    public string Name { get; set; }

}
public class DeviceOption<T> : DeviceOption where T : IComparable
{
    private T _value;

    public T Value
    {
        get { return _value; }
        set
        {
            if (value.CompareTo(_value) == 0) { return; }

            HasChanges = true;
            OriginalValue = _value;
            _value = value;
        }
    }

    public T OriginalValue { get; set; }

}`

更新:我想出来了。 我想通了。事实证明发生了无效的演员表,而且代码是错误的。奇怪的是,异常没有被抛出。我现在知道了,因为我将代码包装在try / catch中。该行为就好像此代码在单独的线程上运行一样。这是LINQ的工作原理吗?

强制转换的原因是因为_deviceOptions是一个List并且包含派生类型,例如DeviceOption或者等等。通过将它添加到LINQ,现在情况很好:'&amp;&amp; d是DeviceOption'

这是更新的代码以及我如何修复无效的演员表:

try
        {

            foreach( DeviceOption<int> d in _deviceOptions.Where( d => d.HasChanges && d is DeviceOption<int>) )
            {
                //blah blah blah
            }



        }
        catch(Exception ex)
        {
            //this is how I detected the exception. Don't ask why I didn't think of this before :(
            Console.Write( ex.Message );
        }

2 个答案:

答案 0 :(得分:1)

似乎没有HasChanges为True的设备选项。在这种情况下,Where扩展方法会产生一个空的可枚举。

答案 1 :(得分:0)

好吧,根据您提供的信息,我必须假设此查询返回一个空的可枚举:

_deviceOptions.Where(d => d.HasChanges)

您是否根本使用过调试器来查看究竟发生了什么?将查询拉出循环表达式并查看它包含的内容。