简体   繁体   中英

Can a class return a static instance of itself? (in c#)

Right now my class is set up as:

enum Unit{Inches,Centimeters};

Later on I have a step that sets all of the properties of each of these units into my classes instance variables. For example:

int unitBase; //10 for metric, 16 for american
int label;
switch(unit)
{
    case Unit.Inches: unitBase = 16; unitLabel = "\"";break;
    case Unit.Centimeters: unitBase = 10; unitLabel = "cm";break;
}

I would rather store this all in a Unit class or struct. Then, I would like to be able to access it in the same way you access colors, for example. You say Color.Blue for a blue color, I would like to say Unit.Inches for inches... That is why I dont make a unit base class and simply extend it.

I know that there is a way to do this! Could anyone enlighten me?

Thanks!

You can use static properties:

public enum UnitSpecifier{Inches,Centimeters};

public class Unit
{
    int unitBase; //10 for metric, 16 for american
    string unitLabel;

    public Unit(UnitSpecifier unit)
    {
        switch (unit)
        {
            case UnitSpecifier.Inches: unitBase = 16; unitLabel = @"\"; break;
            case UnitSpecifier.Centimeters: unitBase = 10; unitLabel = "cm"; break;
        }
    }

    public static readonly Unit Inches = new Unit(UnitSpecifier.Inches);
}
public struct Unit {
    public static readonly Unit Inches = new Unit(16, "\"");
    public static readonly Unit Centimeters = new Unit(10, "cm");

    private readonly int _unitBase;
    private readonly string _unitLabel;

    static Unit() { }

    private Unit(int unitBase, string unitLabel) {
        this._unitBase = unitBase;
        this._unitLabel = unitLabel;
    }

    public int UnitBase {
        get { return this._unitBase; }
    }

    public string UnitLabel {
        get { return this._unitLabel; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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