开发者

defining Function on individual enum constants

开发者 https://www.devze.com 2023-04-04 20:10 出处:网络
one of my class has enum as one of its properties and the definition of the class looks like this: public class A

one of my class has enum as one of its properties and the definition of the class looks like this:

public class A
{

    string properrty1;
    int id;
    CustomEnum enum;

    public A()
    {
      //initialize the properties

    }

}

Thus based on the enum type the class I need this class to call a function that will access some of the properties of the class and perform actions with it.

What would be the best approach for that?

I was thinking of having an interface as one of the properties of the class and then instantiate the interface in the constructor of the class based on the enum and when needed I can do classObject.interface.interfaceImplementation();

Does that sound like a good approach? If yes can you suggest a good way to initialize the interface except for using a bunch of switch case statements that will instantiate the appropriate开发者_如何学C implementation of the interface for that tagtype.


One option would be to have a Dictionary<CustomEnum, Action>:

private static readonly Dictionary<CustomEnum, Action<A>> Actions =
{
    { CustomEnum.Foo, FooAction },
    { CustomEnum.Bar, BarAction },
    { CustomEnum.Baz, BazAction },
};

private static void FooAction(A a) { ... }
private static void BarAction(A a) { ... }
private static void BazAction(A a) { ... }

public void DoSomething()
{
    Actions[enumValue](this);
}

It really depends on what these functions are meant to do, etc. If the action is really inherent in the enum itself, you may want to create a "smart enum" which is basically a fixed set of values, but it's a class with behaviour. This is a bit like a Java enum, but C# as a language doesn't have much support.

See DateTimeFieldType in Noda Time for an example of this. That only has properties, it could easily have methods, and they could be abstract with concrete private subclasses nested within there - a bit like ZoneLocalMapping, also within Noda Time - but in that case it's a factory with three different implementations instead of three specific values.


First off, what's wrong with switch statements? If all you do is call a function, just put a switch in there and call it appropriately -- there's no need for interfaces or anything else. Don't overengineer it.

Now if you have good reason to not go with this approach, the other alternative to switch is a Dictionary<CustomEnum, T> where T is something appropriate to what you need to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消