简体   繁体   中英

Dictionary as an Enum

The BasicTypes.xsd from the GML schema includes the following:

<simpleType name="SignType">
    <annotation>
        <documentation>
        gml:SignType is a convenience type with values "+" (plus) and "-" (minus).
        </documentation>
    </annotation>
    <restriction base="string">
        <enumeration value="-"/>
        <enumeration value="+"/>
    </restriction>
</simpleType>

The code generator (sparx enterprise architect) is generating the following:

namespace OGC.GML.BasicTypes {
    /// <summary>
    /// gml:SignType is a convenience type with values "+" (plus) and "-" (minus).
    /// </summary>
    public enum SignType : int {
        -,
        +
    }
}

Ofcourse, i can't have - and + as enum keys. So my question is:

How would i define a Dicionary object to satisfy the schema as it is? Or is there a better way? Please give code example.

It looks like these people are using an array .

Here's a sample of how to use a dictionary. What a dictionary basically does is it maps one object to another, in this case, string to int, you can always use different types for the keys and values if you like.

        Dictionary<string, int> SignType = new Dictionary<string, int>();
        SignType.Add("-", 0);
        SignType.Add("+", 1);

        int plusValue = SignType["+"];

EDIT: I've updated it again

Now you can use a static class like so

namespace OGC.GML.BasicTypes
{
    public static class SignType
    {
        public static Dictionary<string, int> Values = new Dictionary<string, int>();
        static SignType()
        {
            Values.Add("-", 0);
            Values.Add("+", 1);
        }
    }
}

and you'll have to type OGC.GML.BasicTypes.SignType.Values["+"]

Or, you can use an instance class

    public class SignType
    {
        private static Dictionary<string, int> Values = new Dictionary<string, int>();
        public SignType()
        {
            Values.Add("-", 0);
            Values.Add("+", 1);
        }
        public int this[string s]
        {
            get { return Values[s]; }
        }
    }
}

which will allow `new OGC.GML.BasicTypes.SignType()["+"]'

and even if BasicTypes is a class instead of a namespace, it's still possible to put more Enums and Sub-Classes inside of it, but that might not be the ideal solution, depending on the purpose of the namespace.

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