嵌入式语句错误 [英] Embedded statement error

查看:89
本文介绍了嵌入式语句错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的自定义列表类,我正在尝试对它实现IComparable,但是说实话,它不起作用.我尝试了MSDN和其他博客,但还是一样.

I have a simple custom list class and I am trying to implement IComparable to it, but it's not working to be honest. I tried MSDN and other blogs and still same.

public class sortDateTime : IComparable
{
    protected DateTime m_startDate, m_endDate;

    public DateTime startDate
    {
        get { return m_startDate; }
        set { m_startDate = startDate; }
    }

    public DateTime endDate
    {
        get { return m_endDate; }
        set { m_endDate = endDate; }
    }

    public int CompareTo(object obj)
    {
        if(obj is sortDateTime)
            sortDateTime sDT = (sortDateTime) obj; //here ERROR

         return m_stDate.CompareTo(sDT.m_stDate);
    }
}

按照此示例,但出现错误:

嵌入式语句不能是声明或带标签的语句

Embedded statement cannot be a declaration or labeled statement

推荐答案

请看一段代码,导致错误:

Please take a look at the piece of code, resulting in an error:

if(obj is sortDateTime)
    sortDateTime sDT = (sortDateTime) obj; //here ERROR

return m_stDate.CompareTo(sDT.m_stDate);

您的意思是:

if the object is of type 'sortDateTime'
    Allocate memory for variable 'sDT'
    Cast 'obj' to type 'sortDateTime' 
    Store the result in variable 'sDT'

然后您就离开了作用域-不再需要该变量了(将其分配在堆栈"上并释放它).这根本不符合逻辑.这是一个操作,无需执行任何操作.您要执行的操作如下:

And then you are leaving the scope - the variable is not needed anymore (it's allocated on the 'Stack' and get's released). This does not make sense. It's an operation, that get's executed for nothing. What you want to do is the following:

// Variable for remembering the "cast result" after the cast
sortDateTime sDT = null;

if (obj is sortDateTime)
    sDT = (sortDateTime)obj;  // Cast the object.
else
    return 0;                 // "obj" is not an "sortDateTime", so we can't compare.

// Return the comparison result, if we can compare.
return m_stDate.CompareTo(sDT.m_stDate);

编译器会注意到您无法执行此类操作,并引发错误.但这会编译:

The compiler notices that you cannot do such an operation and throws you an error. However this would compile:

if (obj is sortDateTime)
{
    sortDateTime sDT = (sortDateTime)obj;
}

但也没有意义,并导致编译器错误

but it would not make sense either, and lead to an compiler error at

m_stDate.CompareTo(sDT.m_stDate);  // sDT is not a variable in scope.

这是我实现方法的方式:

This is how I would implement the method:

sortDateTime sDT = obj as sortDateTime;  // 'as' leads to an casted object, or null if it could not cast

if (sDT == null)
    throw new NotSupportedException("The object is not an sortDateTime");
else
    return m_stDate.CompareTo(sDT.m_stDate);

干杯!

这篇关于嵌入式语句错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆