简体   繁体   English

c#覆盖类型比较“是”?

[英]c# override type comparison "is"?

I'm trying to do something here and I may not be doing it right...我正在尝试在这里做一些事情,但我可能做得不对......

I have a base class "Damage", and a derived class "Melee : Damage", and another derived class "Ranged : Damage".我有一个基类“Damage”,一个派生类“Melee:Damage”,以及另一个派生类“Ranged:Damage”。

Then I have a "Unit" class, and a derived class "Warrior : Unit", and another derived class "archer : Unit".然后我有一个“Unit”类,一个派生类“Warrior:Unit”,以及另一个派生类“archer:Unit”。

So the unit class could be either a warrior which would be melee, or an archer which would be ranged.所以单位职业可以是近战的战士,也可以是远程的弓箭手。

So in my Unit class, I define a variable of type "Public Damage dmg".因此,在我的 Unit 类中,我定义了一个类型为“Public Damage dmg”的变量。

Then in the constructor for Warrior, I set the "this.dmg = new Melee(dmg_amount);"然后在 Warrior 的构造函数中,我设置了“this.dmg = new Melee(dmg_amount);” and in the constructor for archer, I set the "this.dmg = new Ranged(dmg_amount);"在 archer 的构造函数中,我设置了“this.dmg = new Ranged(dmg_amount);”

Now I start passing around this unit.dmg variable throughout my code, and in some places I no longer really know that it's an archer or a warrior anymore, I just know the damage.现在我开始在我的代码中传递这个 unit.dmg 变量,在某些地方我不再真正知道它是弓箭手还是战士,我只知道伤害。 So what I'm trying to do is check the damage type, via some code such as:所以我要做的是通过一些代码检查损坏类型,例如:

if (unit.dmg is Melee) {}

However, it tells me that "the given expression is never the provided ('Melee') type".但是,它告诉我“给定的表达式永远不是提供的('Melee')类型”。

and I can understand why: I declared this.dmg to be of type "Damage".我可以理解为什么:我将 this.dmg 声明为“损坏”类型。 I guess I was hoping that when I set it to = new Melee() then it would forever remember that it is Melee damage, without further ado.我想我希望当我将它设置为 = new Melee() 时,它会永远记住它是近战伤害,不用多说。

What is the easiest way to know that the Damage is Melee?知道伤害是近战的最简单方法是什么?

Thanks for the comments guys.谢谢你们的评论。 When I saw the +1's that it should work, I looked again and found my problem.当我看到它应该工作的 +1 时,我再次查看并发现了我的问题。 I had tried to test it with this line of code:我曾尝试用这行代码测试它:

Debug.Write("Does this.dmg == Melee?" + this.dmg is Melee));

Which of course gave the error, because I forgot the brackets.这当然给出了错误,因为我忘记了括号。 I corrected it to:我更正为:

Debug.Write("Does this.dmg == Melee?" + (this.dmg is Melee)));

and the problem is gone.问题就解决了。 I also took the time to test it various ways to make sure, and definitely this works.我还花时间以各种方式对其进行测试以确保它确实有效。 If I set it to this.dmg = Ranged(), then it no longer is "true" that it is Melee, and vise versa.如果我将它设置为 this.dmg = Ranged(),那么它是近战就不再是“真”,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM