2017-04-27 82 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