繁体   English   中英

C#:如何覆盖/替换变量 inheritance

[英]C#: How to override/replace a variables inheritance

这是一个奇怪的问题,我知道你不能覆盖 C# 中的变量。也许这行不通。 我正在尝试获取一个类型为 class 的变量,并用该 class 的子项覆盖它。

在上下文中,我有一个Character class。它有一个类型为AttackSystem attackSystem 我有一个继承自CharacterNPC class,我试图将attackSystem覆盖为继承自AttackSystemNPCAttackSystem类型。

这可行吗? 或者,我是不是把事情复杂化了? 我不应该“覆盖”变量,而只是在NPC的构造函数中说attackSystem = new NPCAttackSystem()

(A)我在做什么(不起作用):

public class Character
{
    public AttackSystem attackSystem = new AttackSystem();
}

public class NPC : Character
{
    public NPCAttackSystem attackSystem = new NPCAttackSystem();;
}

public class AttackSystem {}
public class NPCAttackSystem: AttackSystem {}

(B)我应该做什么?

public class Character
{
    public AttackSystem attackSystem = new AttackSystem();;
}

public class NPC : Character
{
    NPC()
    {
        attackSystem = new NPCAttackSystem();
    }
}

public class AttackSystem {}
public class NPCAttackSystem: AttackSystem {}

我经常在我自己的问题中回答我自己的问题。 只是想知道我是否可以按照我想要的方式来做(A)或者我是否应该以其他方式来做(B)。 另一种方式 (B) 行得通吗? 我可以通过这种方式访问NPCAttackSystem的成员吗?

抱歉所有问题,一个简单的 A.) 或 B.) 就可以了。

感谢您的帮助,我喜欢在这里提问。

你可以这样做:

public class Character
{
    public Character() : this(new AttackSystem())
    {
    }

    protected Character(AttackSystem attackSystem)
    {
        AttackSystem = attackSystem;
    }

    public AttackSystem AttackSystem { get; }
}

public class NpcCharacter : Character
{
    public NpcCharacter() : base(new NpcAttackSystem())
    {

    }
}

考虑如下的方法。 这种方法的主要好处是编译器知道npc.AttackSystemNPCAttackSystem类型(或者至少是可以安全地转换为 NPCAttackSystem 的类型)。

using System;
                    
public class Program
{
    public abstract class Character<T> where T: AttackSystem, new()
    {
        public T AttackSystem { get; } = new T();
    }

    public class PC: Character<AttackSystem>
    {
    }
    
    public class NPC : Character<NPCAttackSystem>
    {
    }

    public class AttackSystem {}
    public class NPCAttackSystem: AttackSystem {}
    
    public static void Main()
    {
        var normal = new PC();
        var npc = new NPC();
        
        Console.WriteLine(normal.AttackSystem.GetType());
        Console.WriteLine(npc.AttackSystem.GetType());
    }
}

暂无
暂无

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

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