正确的代码或设计模式,以从枚举中选择项目的组合

时间:2017-05-25 07:34:34

标签: c# oop design-patterns enums

我想根据一些参数从枚举中选择多个项目。所以,例如假设我有一个名为Animal的枚举

public enum Animal
{
   [DisplayName("Dog")]
   Dog,
   [DisplayName("Cat")]
   Cat,
   [DisplayName("Mouse")]
   Mouse,
   [DisplayName("Ant")]
   Ant,
   [DisplayName("Monkey")]
   Monkey
}

我想根据参数得到这个枚举中的特定项目,所以如果我的参数是“FourLegged”我应该得到Dog,Cat,Mouse,对于其他参数我应该得到不同的设置。并且可以有枚举和参数的多种组合,我可以传递一个或多个参数来从枚举中获取相关项目。

实施此项目的最佳/正确方法应该是什么?是否有任何代码或设计模式来实现这一点?它可以是使用枚举的其他方法。

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

class Program
{
    static void Main(string[] args)
    {
        var t = typeof(Animal);

        foreach (MemberInfo item in t.GetMembers(BindingFlags.Static | BindingFlags.Public))
        {
            if (Attribute.IsDefined(item, typeof(FourLeggendAttribute)))
            {
                // do something
            }
        }
    }
}

public enum Animal
{
    [FourLeggend]
    Dog,
    [FourLeggend]
    [AnotherOne]
    Cat,
    [FourLeggend]
    Mouse,
    [AnotherOne]
    Ant,
    Monkey
}

public class AnotherOneAttribute : Attribute
{
}

public class FourLeggendAttribute : Attribute
{
}

答案 1 :(得分:0)

摘要

关键的想法是为每个想要描述的事物使用特定的方法。其中一个实现是使用静态方法(如

)创建辅助类
class AnimalHelper { 
  public static bool isFourLegged(Animal a) {//your code here}  
}

并调用if (AnimalHelper.isFourLegged(dog) 但是这不是一个好主意:在OOP中每只狗应该知道他的腿而且其他任何人都不应该计算它的腿,但问狗'如何你有很多腿?'。我想,使用帮手是邪恶的。可能它是一个较小的邪恶,但它无论如何都不好。

在Java世界(我来自哪里),每个枚举都是一个正确的类,你可以添加你想要的任何方法,并在每个Animal内有任意数量的属性。

性状

在C#中你可以添加一个methods to your enum as trait,这样你就可以加入Animal其他知识

// great idea to put it in the one file with Animal if possible
public static class Extensions { 
  public static bool isFourLegged(this Animal animal) {
     // an example for using hardcoded values. 
     // You should alter this method when you add another Animal
     return animal == Animal.Dog && animal == Animal.Mouse
     // oops, someone added Cat after me
  }
  public static Collection<Animal> getAllFourLegged {
     // use dynamic way like in answer from Andrea is good
     // but *probably* cause perfomance issues
  }

并像if (dog.isFourLegged())一样使用它。

类层次结构

如果您的Animal有许多属性,并且您希望它有某些行为(例如aCat.eat(aMouse)aDog.go(aPlace)),那么您可能希望创建类层次结构class Cat extends Animal然后创建枚举AllCreatures。这为您提供了更大的灵活性,以降低复杂性的成本

请注意我是C#世界中的陌生人,可能会错过重要的内容