2017-04-27 162 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; 
      }