简体   繁体   English

创建一个没有默认值和值的属性类

[英]Creating a property class with no default value and with value

I'm trying to create a property class with a default value and no value.我正在尝试创建一个具有默认值但没有值的属性类。 Is this right?这是正确的吗? If I want a property with no value I'll just call GameLevel class and if I want a property with default value I'll just call GameLevelWithDefaultValue如果我想要一个没有值的属性,我将只调用 GameLevel 类,如果我想要一个具有默认值的属性,我将只调用 GameLevelWithDefaultValue

public abstract class GameLevel
{
    public abstract int nextLevelToUnlock { get; set; }

    public abstract List<LevelDetails> levelDetails { get; set; }
}

class GameLevelWithDefaultValue : GameLevel
{
    public override int nextLevelToUnlock { get; set; } = 1;

    public override List<LevelDetails> levelDetails { get; set; } = new List<LevelDetails>()
    {
        new LevelDetails{levelIndex = 1, Stars = 0 },
        new LevelDetails{levelIndex = 2, Stars = 0 },
        new LevelDetails{levelIndex = 3, Stars = 0 }
    };
}

public class LevelDetails
{
    public int levelIndex { get; set; }
    public int Stars { get; set; }
}

I meant something like this:我的意思是这样的:

public class GameLevel
{
    public int NextLevelToUnlock { get; set; }
    public List<LevelDetails> LevelDetails { get; set; }

    public GameLevel() { }

    public GameLevel(int nextLevelToUnlock, List<LevelDetails> levelDetails)
    {
        NextLevelToUnlock = nextLevelToUnlock;
        LevelDetails = levelDetails;
    }
}

public class LevelDetails
{
    public int LevelIndex { get; set; }
    public int Stars { get; set; }

    public LevelDetails(int levelIndex, int stars)
    {
        LevelIndex = levelIndex;
        Stars = stars;
    }
}

public static class GameLevelBuilder
{
    public static GameLevel BuildGameLevelWithDefaultValue()
    {
        var defaultLevelDetail = new List<LevelDetails>()
        {
            new LevelDetails(1, 0),
            new LevelDetails(2, 0),
            new LevelDetails(3, 0)
        };

        return new GameLevel(1, defaultLevelDetail);
    }
}

When you need the object with the default value, you'll let the GameLevelBuilder create the object for you, while when you need the object without passing the initial values, you'll use the parameterless constructor of GameLevel .当您需要具有默认值的对象时,您将让GameLevelBuilder为您创建对象,而当您需要对象而不传递初始值时,您将使用GameLevel的无参数构造函数。

You cannot instantiate an abstract class.您不能实例化抽象类。 If you inherit an abstract class, you must override it's abstract properties.如果继承抽象类,则必须重写它的抽象属性。 So, the value of nextLevelToUnlock and levelDetails depends on the child class.因此, nextLevelToUnlocklevelDetails的值取决于子类。 Also, default value for class in C# is null, or the result of it's zero parameter constructor for value types.此外,C# 中类的默认值为 null,或者它是值类型的零参数构造函数的结果。 If you don't assign any value to a field, it will get it's default value.如果您没有为字段分配任何值,它将获得默认值。

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

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