2017-04-27 48 views
-1

因此,這裏是我的代碼,爲什麼C#向下變爲始終爲空?

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, 

我使用Unity引擎現在。所以如果運行這段代碼,我得到了 Debug.Log(「Menu name is」+ menu.Name);和「 Debug.Log(」Stat event is null,name is「+ thisSpot.Name);都。 爲什麼? 菜單不爲空,但在翻倒後,它變爲空? 我不明白這是爲什麼。

所以在這段代碼中,我想執行以下代碼[1]的一部分,但[statEvent]爲空, 因此,所有下面的代碼不會被調用(繼續關鍵字)

爲什麼垂頭喪氣變成空?

請幫忙。

+0

它爲null,因爲菜單是不是一個'StatEvent'它是一個'SpotUIBase'和,至於你的代碼所示,一個'SpotUIBase'不擴展或實現任何其他類或接口。你是否試圖將'menu.uiSort'強制轉換爲'StatEvent'? – Lithium

+0

你有你的空檢查錯誤。你在檢查它是否爲空之前訪問'menu.uiSort' if(menu!= null)Debug.Log(「Menu name is」+ menu.Name);'。 – bradbury9

+0

因此,StatEvent繼承自SpotUIBase .. 公共類StatEvent:SpotUIBase { – leegod

回答

0

因此,我使用Google搜索並確認了Downcast方法,並將foreach更改爲語法。 並解決。

這是更改後的代碼。

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