类和对象继承

Cod*_*ack 0 c# inheritance class

更新

好的,所以我正在玩类和继承,我正在尝试做一些我以前在一个源代码是C++的游戏中做过的事情,我想知道这里是否有人可以帮助我理解如何用C#来做.

我想做的是两件事:

首先当我创建某个类的对象时,我想将一个整数传递给构造函数,并使用该整数来确定将初始化哪个sublcass.

像这样:职业newVoc = new Vocation(1); 并且1将选择具有该VocationId的第一个sublcass或子类.

第二件事,我已经有一个从Creature Class继承的Player类,但是我希望Player Class本身包含一个Vocation对象.所以我可以设置职业,当我进行属性更改并且播放器具有不同的属性时...这是示例代码,试图用我所说的,希望有人理解我的意思.

好的,我现在收到错误.无法隐式转换类型Mage' toVocation'

这就是我得到的......

Vocation.cs

using UnityEngine;
using System.Collections;

public enum VocationType { Mage, Warrior }

public class Vocation
{

}

public static class VocationFactory
{
    public static Vocation CreateVocation(VocationType type)
    {
        switch (type)
        {
            case VocationType.Mage:
                {
                    return new Mage();
                    break;
                }
        }
    }
}

public class Mage
{
    public string Name = "Mage";

    public Mage()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

Player.cs

using UnityEngine;
using System.Collections;

public class Player : Creature 
{
    public uint Level {get; set; }
    public uint Dexterity {get; set; }
    public uint Vitality {get; set; }
    public uint Intelligence {get; set; }
    public uint Strength {get; set; }
    public ulong Experience {get; set;}

    public Player()
    {
        var voc = VocationFactory.CreateVocation(VocationType.Mage);
        Level = 1;
        Health = 500;
        MaxHealth = 100;
        Mana = 50;
        MaxMana = 100;
        Experience = 0;
        Dexterity = 0;
        Vitality = 0;
        Intelligence = 0;
        Strength = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 5

您不应该从基类创建对象.请改用工厂,也可以使用枚举来定义类型.

如果您从上一个问题的Dmitry答案开始,您可以创建一个实例化对象的工厂类.例如:

public enum VocationType { Mage, ... }

public static class VocationFactory
{
    public static Vocation CreateVocation(VocationType type)
    {
        switch (type)
        {
            case VocationType.Mage:
                {
                    return new Mage();
                    break;
                }
        }

        throw new Exception($"You did not implement type '{type}'.");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样称呼它:

var voc = VocationFactory.CreateVocation(VocationType.Mage);
Run Code Online (Sandbox Code Playgroud)