-7

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

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);
    }
}

遵循此示例,但收到错误:

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

4

4 回答 4

4

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

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'

然后您将离开范围-不再需要该变量(它在“堆栈”上分配并被释放)。这根本不符合逻辑。这是一个操作,它会被白白执行。您想要做的是以下内容:

// 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);

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

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

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

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

这就是我将如何实现该方法:

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);

干杯!

于 2013-04-11T10:47:22.117 回答
2

在不检查您的逻辑的情况下,我将修复语法错误。

这:

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

    return m_stDate.CompareTo(sDT.m_stDate);
}

应该:

public int CompareTo(object obj)
{
    if (obj is sortDateTime)
    {
        sortDateTime sDT = (sortDateTime) obj;
        return m_startDate.CompareTo(sDT.m_startDate);
    }
    else
    {
        throw new ArgumentException("object is not a sortDateTime ");   
    }
}

更仔细地查看您链接的页面。你没有正确地遵循它。

于 2013-04-11T10:46:06.060 回答
0

这样做:

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

它会消失的。

有关编译器为何以这种方式运行的更具体解释,请查看: Why this compile error

遵循C#标准命名约定:不要以非大写字母开头的类型命名,因此请更改sortDateTime->SortDateTime

于 2013-04-11T10:42:11.273 回答
0

试试这个:

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

    if(sDT != null)
    {
        return m_stDate.CompareTo(sDT.m_stDate);
    }
    else
    {
        throw new ArgumentException("object is not a sortDateTime type.");
    }
}
于 2013-04-11T10:51:32.573 回答