2017-04-27 66 views
0

我挣扎了一下,在这里我将如何检查了解迭代一块,如果若跌破entity变量在变量comps所有Enum.Component。如果我知道只有一个组件通过.ForEach和基本比较(例如entity.ForEach(comp => Console.WriteLine(comp.COMPONENT == Enum.Component.EXPERIENCE));),我可以比较直接地实现,但如果需要检查多个组件,则不会。检查实体包含所有组件通过枚举标志

我想了解的C#好一点细微的差别,所以我不想蛮力这与实际foreach(在常规foreach(var x in exes)类型的方式)或类似的东西,但真正要了解我如何通过这些IEnumerable函数并使用lambda表达式来实现这些对象。因此,我需要一个利用这些东西的答案,除非这在技术上是不可行的,尽管可能是这样,我猜测。

// The Component.IComponent Interface (it's in the Component namespace) 
interface IComponent { 
    Enum.Component COMPONENT { 
     get; 
    } 
} 

// The Enum.Component (it's in the Enum namespace) 
enum Component { 
    EXPERIENCE, 
    HEALTH 
} 

// The Component.Experience (it's in the Component namespace) 
class Experience : IComponent { 
    public ThresholdValue xp; 
    public int level; 

    public Enum.Component COMPONENT { 
     get { 
      return Enum.Component.EXPERIENCE; 
     } 
    } 
} 

// It probably doesn't matter, but ENTITY_MANAGER is this type 
Dictionary<Guid, List<Component.IComponent>> 


// Trial code beings here: 
Guid GUID = new Guid(); 
ENTITY_MANAGER.getEntities().Add(GUID, new List<Component.IComponent> { new Component.Experience(50, 3), new Component.Health(20, 25) }); 
List<Component.IComponent> entity = ENTITY_MANAGER.getEntities()[new Guid()]; 

Enum.Component[] comps = new Enum.Component[] { 
    Enum.Component.EXPERIENCE, 
    Enum.Component.HEALTH 
}; 

// This is where I don't know what to do and know this is wrong 
comps.All(v => entity.ForEach(comp => Console.WriteLine(comp.COMPONENT == v))); 
+0

你可以在实体中使用select! https://msdn.microsoft.com/en-us/library/jj573936(v=vs.113).aspx –

回答

2

你可以很容易地通过标志做到这一点!

https://msdn.microsoft.com/en-us/library/system.flagsattribute(v=vs.110).aspx

首先做到这一点与您的枚举:

[Flags] 
enum Component { 
    None = 0, 
    EXPERIENCE = 1 << 0, 
    HEALTH = 1 << 1, 
    All = (1 << 2) - 1 
} 

这基本上将您的值存储为2的幂,与“所有”是所有标志的总和,在这种情况下精通和惠普1和2,所以一切都是3(1 + 2)

现在你可以做到这一点在你的实体类:

public Enum.Component Flags => comps.Select(c => c.Component).Distinct().Sum(); 
public bool HasAllFlags => Flags == Enum.Component.All; 

我们将所有不同的基础枚举为2,所有下一步-1,这意味着全部是所有枚举列表的总和。然后我们总结一下Enums(我们可能必须首先转换为int然后返回到枚举,我不记得是否可以在C#中一起添加Enums),并检查它们是否为== Component组件。所有。

你走了!

+0

感谢您的帮助,'[Flags]'属性真的有所帮助。我一直得到一个“comps”在这个范围内不可用的错误类型,但是能够在更高级别使用你的建议来完成这个任务:'Enum.Component flags = Enum.Component.EXPERIENCE | Enum.Component.HEALTH; (Enum.Component)entity.Sum(e =>(int)e.COMPONENT); Console.WriteLine((mask&flags)== flags);' – Matt