日期转换中的NullReference异常

时间:2013-07-16 08:44:55

标签: c#

我正在进行HijriGreogian日期转换。但是,我收到此NullReferenceException并显示错误消息:

  

对象引用未设置为对象的实例。

pprivate HttpContext cur;

    private const int startGreg=1900;
    private const int endGreg=2100;
    private string[] allFormats={"yyyy/MM/dd","yyyy/M/d",
        "dd/MM/yyyy","d/M/yyyy",
        "dd/M/yyyy","d/MM/yyyy","yyyy-MM-dd",
        "yyyy-M-d","dd-MM-yyyy","d-M-yyyy",
        "dd-M-yyyy","d-MM-yyyy","yyyy MM dd",
        "yyyy M d","dd MM yyyy","d M yyyy",
        "dd M yyyy","d MM yyyy"};
    private CultureInfo arCul;
    private CultureInfo enCul;
    private HijriCalendar h;
    private GregorianCalendar g;

    public void Dates()
    {
        cur = HttpContext.Current;


        arCul=new CultureInfo("ar-SA");
        enCul=new CultureInfo("en-US");

        h=new  HijriCalendar();
        g=new GregorianCalendar(GregorianCalendarTypes.USEnglish);

        arCul.DateTimeFormat.Calendar=h;

    }

    public string HijriToGreg(string hijri)
    {

        if (hijri.Length<=0)
        {

            cur.Trace.Warn("HijriToGreg :Date String is Empty");
            return "";
        }
        try
        {

            DateTime tempDate=DateTime.ParseExact(hijri,allFormats,
               arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
            return tempDate.ToString("yyyy/MM/dd",enCul.DateTimeFormat);
        }
        catch (Exception ex)
        {
            cur.Trace.Warn("HijriToGreg :"+"\n"+ex.ToString());
            return "";
        }
    } 

3 个答案:

答案 0 :(得分:1)

这意味着某处您正在访问null的引用类型变量上的字段,属性或方法(或访问.Value上的Nullable<T>结构)。我们不能告诉你哪里,但是ex.StackTrace可以,也可以添加一个断点并单步执行错误附近的代码,查看流氓null(或< em>正确 null,缺少null - 检查)

答案 1 :(得分:0)

WhatEver cur = new WhatEver();

答案 2 :(得分:0)

这意味着您正在使用对象而不进行初始化。使用new关键字初始化它。