Невозможно привести объект типа 'Common.Date' к типу 'System.IConvertible C # - PullRequest
0 голосов
/ 22 октября 2011

Я видел эту проблему с сообщением об ошибке в stackoverflow, но ни один из них не был предназначен для даты-времени или типа даты, чтобы работать только с типом даты. Я создал класс типа даты и написал несколько перегрузок для него в классе даты.,Мой класс дат:

using System;
namespace Common 
{
    public class Date
    {
        private DateTime _d1;

        public Date(DateTime dateTime)
        {
            _d1 = dateTime;
        }

        public static bool operator <(Date date1, Date date2)
        {
            bool flag = false;


            //Now, get the original DateTime Type of C#
            DateTime firstDate = Convert.ToDateTime(date1);
            DateTime secondDate = Convert.ToDateTime(date2);

            //Now compare the two DateTime variables and assign the flag to true 
            //if the first date is smaller than the second date
            int result = DateTime.Compare(firstDate, secondDate);
            if (result < 0)
            {
                flag = true;
            }
            return flag;
        }

        public static bool operator >(Date date1, Date date2)
        {
            bool flag = false;

            //Now, get the original DateTime Type of C#
            DateTime firstDate = Convert.ToDateTime(date1);
            DateTime secondDate = Convert.ToDateTime(date2);

            //Now compare the two DateTime variables and assign the flag to true 
            //if the first date is Greater than the second date
            int result = DateTime.Compare(firstDate, secondDate);
            if (result > 0)
            {
                flag = true;
            }
            return flag;
        }

        public static bool operator <=(Date date1, Date date2)
        {
            bool flag = false;

            //Now, get the original DateTime Type of C#
            DateTime firstDate = Convert.ToDateTime(date1);
            DateTime secondDate = Convert.ToDateTime(date2);

            //Now compare the two DateTime variables and assign the flag to true 
            //if the first date is Greater than the second date
            int result = DateTime.Compare(firstDate, secondDate);
            if (result <= 0)
            {
                flag = true;
            }

            return flag;
        }

        public static bool operator >=(Date date1, Date date2)
        {
            bool flag = false;

            //Now, get the original DateTime Type of C#
            DateTime firstDate = Convert.ToDateTime(date1);
            DateTime secondDate = Convert.ToDateTime(date2);

            //Now compare the two DateTime variables and assign the flag to true 
            //if the first date is Greater than the second date
            int result = DateTime.Compare(firstDate, secondDate);
            if (result >= 0)
            {
                flag = true;
            }
            return flag;
        }

        public static bool operator ==(Date date1, Date date2)
        {
            bool flag = false;

            //Now, get the original DateTime Type of C#
            DateTime firstDate = Convert.ToDateTime(date1);
            DateTime secondDate = Convert.ToDateTime(date2);

            //Now compare the two DateTime variables and assign the flag to true 
            //if the first date is Greater than the second date
            int result = DateTime.Compare(firstDate, secondDate);
            if (result == 0)
            {
                flag = true;
            }
            return flag;
        }

        public static bool operator !=(Date date1, Date date2)
        {
            bool flag = false;

            //Now, get the original DateTime Type of C#
            DateTime firstDate = Convert.ToDateTime(date1);
            DateTime secondDate = Convert.ToDateTime(date2);

            //Now compare the two DateTime variables and assign the flag to true 
            //if the first date is Greater than the second date
            int result = DateTime.Compare(firstDate, secondDate);
            if (result != 0)
            {
                flag = true;
            }
            return flag;
        }
    }//end of class Date
}//End of namespace

, но проблема в том, что я пытаюсь использовать в своем коде за страницей, что это дает мне эту ошибку - Невозможно привести объект типа 'Common.Date' к типу 'System.IConvertible

код, в котором я его использую, например Date purchaseDate = new Date (item.PurchaseDate);Date submissionSate = new Date (item.SubmissionDate);

                    if (purchaseDate>submissionSate)
                    {
                        //to do
                    }

здесь, в объекте item, дата покупки и передачи являются свойствами datetime, и ошибка в строке if Может кто-нибудь дать мне какое-либо предложение?Каково вероятное решение этой проблемы?

Ответы [ 2 ]

2 голосов
/ 22 октября 2011

Вы можете напрямую получить доступ к полям Date. Хотя я ставлю под сомнение полезность этого Date объекта.

public static bool operator <(Date date1, Date date2)
{
    return date1 != null && date2 != null && date1._d1 < date2._d1
}
1 голос
/ 22 октября 2011

При перегрузке > оператора у вас есть

DateTime firstDate = Convert.ToDateTime(date1); 
DateTime secondDate = Convert.ToDateTime(date2);

, и нет перегрузки Convert.ToDateTime, которая принимает ваш Date объект, поэтому вы звоните Convert.ToDateTime(object), что требует object для реализации IConvertible .

Вы можете реализовать IConvertible или просто сравнить значения _d1, как упоминает @ChaosPandion.

...