2017-04-27 2 views
-1

Also hier ist mein Code,Warum C# downcast wird immer null?

public void CheckStatChal()  
{ 
    foreach (SpotUIBase menu in thisSpot.ownMenus) 
    { 
     if (menu.uiSort == SpotUISort.StatEvent) 
     { 
      if(menu != null) 
       Debug.Log("Menu name is "+menu.Name); 
      var statEvent = menu as StatEvent; 
      if (statEvent == null) 
      { 
       Debug.Log("Stat event is null, name is "+thisSpot.Name); 
       continue; 
      } 
      .......... [1] 

public SpecialSpotClass thisSpot; 
public abstract class SpecialSpotClass 
{ 
public List<SpotUIBase> ownMenus = new List<SpotUIBase>(); 
.... 
public class SpotUIBase 
{ 
    public SpotUISort uiSort; 
    .... 
public class StatEvent : SpotUIBase 
{ 
    .... 
public enum SpotUISort{ 
    Inn, Shop, Bar, 

ich jetzt Unity-Engine verwenden. Also, wenn Sie diesen Code ausführen, habe ich Debug.Log ("Menüname ist" + menu.Name); und Debug.Log ("Stat-Ereignis ist null, Name ist" + thisSpot.Name); beide. Warum? Menü ist nicht null, aber nach der es reduziert wird, wird es null? Ich verstehe das nicht warum.

Also in diesem Code möchte ich [1] Teil unterhalb Codes auszuführen, aber [statEvent] ist null, so der gesamte Code unten genannten nicht durch (weiter Schlüsselwort)

Warum gesenkten null geworden?

Hilfe bitte.

+0

Es ist null, weil Menü kein 'ist StatEvent' es ist ein' SpotUIBase' und, so weit wie Sie Ihren Code zeigt ein 'SpotUIBase' nicht verlängern oder eine andere Klasse oder Schnittstelle implementieren. Versuchen Sie, 'menu.uiSort' in' StatEvent' zu konvertieren? – Lithium

+0

Sie haben Ihre Null-Checks falsch. Sie greifen auf 'menu.uiSort' zu, bevor Sie prüfen, ob es null ist. If (menu! = Null) Debug.Log (" Menüname ist "+ menu.Name);'. – bradbury9

+0

So wird StatEvent von SpotUIBase geerbt. public class StatEvent: SpotUIBase { – leegod

Antwort

0

So googelte und bestätigte ich Downcast-Methode, und wechselte foreach für Syntax. Und gelöst.

Hier ist Code geändert.

for (int i = 0; i < thisSpot.ownMenus.Count; i++) 
    { 
     if (thisSpot.ownMenus[i].uiSort == SpotUISort.StatEvent) 
     { 
      thisSpot.ownMenus[i] = SpotUI.Instance.StatEvent; 
      var ownMenu = (StatEvent) thisSpot.ownMenus[i]; 
      Debug.Log("own menu is "+ownMenu.Name); 
      if ((!ownMenu.StatChal1.nowCoolTime && ownMenu.StatChal1 != null) 
              || ownMenu.StatChal1 == null) 
      { 
       StatChallenge.Instance.MakeStatChal(this, ref ownMenu.StatChal1); 
       Debug.Log(ownMenu.StatChal1.Name); 
       ownMenu.SetChalInfo(ownMenu.StatChal1, 1); 
       chal1 = ownMenu.StatChal1; 
      }