无法在“类型”c#上转换对象“type”

时间:2015-04-02 17:27:12

标签: c# casting

我在游戏的服务器端工作,它几乎已经完成了但是今天我遇到了一个问题...这个游戏是基于2种形式,触地得分和死亡竞赛,在结束时游戏服务器必须知道结果。这是一款在线游戏。当我结束比赛或玩家离开时,服务器崩溃,它不应该,它只是回到房间。它给了我以下错误:

[ERROR]: Unable to cast object of type 'B3S.Core.Data.GameScore' to type 'B3S.Core.Data.TDGameScore'.
   in B3S.Core.Data.Player.SetNewTDStats(Boolean win)
   in B3S.Core.Data.Room.BroadcastBriefing(Boolean result)
   in B3S.Core.Data.Room.<BeginResult>d__2b.MoveNext()
--- End of stack trace ---
   in System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__1(Object state)
   in System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   in System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   in System.Threading.ThreadPoolWorkQueue.Dispatch()
   in System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

有人可以帮助我吗?!

这是B3S.Core.Data.GameScore的来源:

public class GameScore
    {
        public DateTime JoinTime { get; set; }
        public uint TotalPoints { get; set; }

        public virtual uint CalculateEXP()
        {
            return 0;
        }
    }

这是B3S.Core.Data.TDGameScore的来源:

public class TDGameScore : GameScore
{
    public uint TDScore { get; set; }
    public uint TDAssists { get; set; }

    public uint Kills { get; set; }
    public uint KillAssists { get; set; }
    public uint Offense { get; set; }
    public uint OffenseAssists { get; set; }
    public uint Defense { get; set; }
    public uint DefenseAssists { get; set; }
    public uint Recovery { get; set; }

    public override uint CalculateEXP()
    {
        var ts = DateTime.Now - JoinTime;
        if (ts.TotalSeconds < 0 || TotalPoints == 0)
            return 0;
        return (uint)ts.TotalSeconds / 4 + (TDScore * 15) + (100 * TotalPoints / (500 + 2 * TotalPoints) * 14);
    }
}

1 个答案:

答案 0 :(得分:1)

TDGameScore是GameScore的子类(派生类)。 最有可能的是,你传递了一个不是TDGameScore的GameScore实例。您必须检查何时创建有问题的实例以及为什么它不是正确的子类型。