开发者

Strange compiler error

quick question really: I have this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hovel {
    public abstract class DamageType {
        public string GetKillString(string instigatorName, string victimName) {
            return killString.Replace("<inst>", instigatorName).Replace("<vict>", victimName);
        }
        protected string killString = "ERROR_NO_KILLSTRING_DEFINED";

        public string GetDamageString(string inst开发者_如何学JAVAigatorName, string victimName) {
            return damageString.Replace("<inst>", instigatorName).Replace("<vict>", victimName);
        }
        protected string damageString = "ERROR_NO_DAMAGESTRING_DEFINED";
    }

    public class DamageType_Default : DamageType {  
        killString = "ERROR_DEFAULT_DAMAGE_TYPE";
        damageString = "ERROR_DEFAULT_DAMAGE_TYPE";
    }
}

To me, that looks fine, but I get this error for the only two lines in DamageType_Default:

Invalid token '=' in class, struct, or interface member declaration

So... What the?


The problem is the following lines

killString = "ERROR_DEFAULT_DAMAGE_TYPE";
damageString = "ERROR_DEFAULT_DAMAGE_TYPE";

These lines occur inside a class definition at the scope reserved for members definitions but are instead normal code statements. You'll need to put these in a method (perhaps a constructor)

public DamageType_Default : DamageType {
  public DamageType_Default() { 
    killString = "ERROR_DEFAULT_DAMAGE_TYPE";
    damageString = "ERROR_DEFAULT_DAMAGE_TYPE";
  }
}


You're defining a class DamageType_Default but you're just putting some code inside it, instead of inside a constructor. I think you meant:

public class DamageType_Default : DamageType {  
  public DamageType_Default() : base() {
    killString = "ERROR_DEFAULT_DAMAGE_TYPE";
    damageString = "ERROR_DEFAULT_DAMAGE_TYPE";
  }
}

which will define a constructor in the base class, and the constructor will set those values to the new overridden ones after constructing the base class.


You're missing a constructor. Specifically, those two lines of code should be in a constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜