简体   繁体   中英

Avoid Error: Object reference not set to an instance of an object

I have the following two functions:

    private object[] GetFormatedDataArray(
            Dienstleistungsreservierung dlres,
            KostenstellenProvider kstProvider)
        {
            SAPKonto konto;
            try { konto = KontierungsProvider.Instance.GetSAPKonto(dlres); }
            catch { konto = new SAPKonto(); konto.KontoText = "UNBEKANNT"; }

            Kostenstelle kst = kstProvider.GetKostenstelle(dlres.Raumreservierung.Buchung);
            KostenstellenValidator.Validate(kst);

            return new object[] {

                dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.KonfStandort,
                dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner.AnsprechPartnerName,  

       ......

}

There is a possibility that the value of:

dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner

is null, for that i have done a if clause around the which creates the .csv file, that he should create the file if the value is null or != null.

With that function/ returning values of that function i create a .csv file.

 {
       .....
        var file = GetCsvFile(dl, accDate);
                    // CSV werden auf Platte geschrieben!
                    var csvWriter = new CSVWriter(file);
                    csvWriter.WriteLine(GetHeader());

                    foreach (Dienstleistungsreservierung dlres in dlDic[dl])
                    {
                        if (dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner == null || dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner != null)
                        {
                            csvWriter.WriteLine(GetFormatedDataArray(dlres, kstProvider));
                        }
                    }
                    csvWriter.Flush();

    ....
    }

But the Error is still there? Is there a other way to get around?

if (dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner == null || 
    dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner != null)

Your if statement contains contradictory check. If there is a possibility that the value of dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner can be null then you should check if its not null then proceed. Something like following

if (dlres.Raumreservierung.VirtualRaum.Etage.Gebaeude.Partner != null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM