为什么C#downcast总是为空?

为什么C#downcast总是为空?,c#,null,downcast,C#,Null,Downcast,这是我的代码 public void CheckStatChal() { foreach (SpotUIBase menu in thisSpot.ownMenus) { if (menu.uiSort == SpotUISort.StatEvent) { if(menu != null) Debug.Log("Menu name is "+menu.Name);

这是我的代码

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,  
public void CheckStatChal()
{
foreach(此Spot.own菜单中的SpotUIBase菜单)
{
if(menu.uiSort==SpotUISort.StatEvent)
{
如果(菜单!=null)
Debug.Log(“菜单名为”+菜单名);
var statEvent=作为statEvent的菜单;
if(statEvent==null)
{
Log(“Stat事件为null,名称为“+thispot.name”);
继续;
}
.......... [1]
公共特价体育课;
公共抽象类SpecialSpotClass
{  
public List own菜单=新建列表();
....
公共类SpotUIBase
{
公共体育运动;
....
公共类StatEvent:SpotUIBase
{
....
公共枚举SpotUISort{
客栈、商店、酒吧,
我现在正在使用Unity引擎。 所以如果运行这个代码,我得到 Debug.Log(“菜单名为”+菜单名);以及 Log(“Stat事件为null,名称为“+thispot.name”);两者都有。 为什么? 菜单不是空的,但向下转换后,它会变成空的吗? 我不明白这是为什么

在这段代码中,我想执行代码下面的[1]部分,但[StateEvent]为空, 所以下面的所有代码都不是由(continue关键字)调用的

为什么下行变为空


请帮忙。

所以我在谷歌上搜索并确认了右下传方法,并将foreach改为for语法。 解决了

这是更改后的代码

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;
            }
for(int i=0;i
它是空的,因为menu不是
StatEvent
它是
SpotUIBase
,而且就您的代码所示,
SpotUIBase
不会扩展或实现任何其他类或接口。您是否试图将
menu.uiSort
转换为
StatEvent
?您的空检查错误。您正在访问
menuiSort
在检查它是否为null之前
如果(menu!=null)Debug.Log(“menu name is”+menu.name);
。因此StatEvent是从SpotUIBase继承的。公共类StatEvent:SpotUIBase{我同意@Lithium。根据我们掌握的信息,
StatEvent
将始终为null,除非您以SpotUIBase的身份执行
menu