Dynamic mapping of enum value (int) to type

前端 未结 4 1182
清酒与你
清酒与你 2020-12-18 09:27

It appeared that this problem is quite common in our job.

We we are sending an int or enum value through the network, then we receive it we would like to create/call

4条回答
  •  有刺的猬
    2020-12-18 09:46

    kogut, I don't propose this as an answer, but since you ask me to expand on my comment on your original question here's a very brief summary of what the .net environment gives you...

    public enum MyEnum
    {
        [MyAttribute(typeof(ClassNone))]
        None,
        [MyAttribute(typeof(ClassOne))]
        One,
        [MyAttribute(typeof(ClassTwo))]
        Two,
        [MyAttribute(typeof(ClassThree))]
        Three
    }
    

    So you have your basic enum One, Two, Three etc. which works just like....er....an enum!

    But you also code up a class called MyAttribute (and in fact for more information in this area, just search for Attributes). But as you can see this allows you to say, at design time, that such-and-such an enum value is associated with such-and-such a class.

    This information is stored in the enum's metadata (the value of a managed environment!) and can be interrogated at runtime (using Reflection). Needless to say this is very powerful, I've used this mechanism to systematically strip out loads of maps of the kind proposed in other answers to your question.

    An example of the usefulness is this...at one client I worked with, the convention was to store statuses as strings in a database on the grounds that they would be more readable to a human who needed to run a table query. But this made no sense in the applications, where statuses were pushed through as enums. Take the above approach (with a string rather than a type) and this transform happened on a single line of code as data was read and written. Plus, of course, once you've defined MyAttribute it can be tagged onto any enum you like.

    My language if choice these days is c# but this would also be good in (managed) c++.

提交回复
热议问题