![](/img/trans.png)
[英]Extension method to convert Flags to IEnumerable<Enum> and conversely (C#)
[英]C# - Help with [Flags] Enum & Extension Method
我有以下枚舉:
[Flags]
public enum PostAssociations
{
None = 0x0,
User = 0x1,
Comments = 0x2,
CommentsUser = 0x3
}
首先,我不確定這些標志是否正確。
我這樣做是為了讓我能流暢地為實體框架定義“包含”(因為EF Include方法采用字符串,我不想向UI公開)。
所以我想要它,以便我的服務層可以接受PostAssociations ,並且在我的服務層中,我利用擴展方法將其轉換為string []。 (然后我的存儲庫拆分以執行.include)。
我對Flags Enum的處理不多,因此對我的無知表示歉意。 :)
這是我想要的“真值表”(枚舉值,轉換后的字符串[])
None = null
User = new string[] { "User" }
Comments = new string[] { "Comments" }
User, Comments = new string[] { "User", "Comments" }
Comments, CommentsUser = new string[] { "Comments", "Comments.User" }
User, Comments, CommentsUser = new string[] { "User", "Comments", "Comments.User" }
沒有評論就不能有CommentUser。
所以我需要三件事的幫助:
當然,如果你們能想到一種更好的方法來做即時嘗試,我也會考慮的。 本質上,我試圖掩蓋Enum后面的EF Include的“魔術字符串”,並且考慮到您可以進行多個include(或不包括),我認為這對於Flags Enum是一個很好的例子。
多謝你們。
如果您創建帶有標志的枚舉:
[Flags]
public enum PostAssociations
{
None = 0x0,
User = 0x1,
Comments = 0x2,
CommentsUser = User|Comments,
}
那會更有意義。 在您當前的代碼中,我不了解您要實現的目標。
否則,我不認為您根本不需要基於標志的枚舉...
我的壞家伙,我對flags枚舉的經驗不足,導致了一個令人困惑的問題。
我的情況不適用於標志枚舉。
相反,我選擇使用PostAssociations []。
我的服務層:
public Post FindSingle(int postId, PostAssociations[] postAssociations)
{
return repo.Find(postAssocations.ToEfInclude()).WithId(postId);
}
擴展方法:
public static string[] ToEfInclude(this PostAssociations[] postAssocations)
{
if (postAssocations == null) return null;
List<string> includeAssociations = new List<string>();
if (postAssocations.Contains(PostAssociations.User))
includeAssociations.Add("User");
if (postAssocations.Contains(PostAssociations.Comments))
{
if (postAssocations.Contains(PostAssociations.CommentsUser))
{
includeAssociations.Add("Comments.User");
}
includeAssociations.Add("Comments");
}
return includeAssociations.ToArray();
}
用法:
PostAssociations[] associations = new[] { PostAssociations.Comments, PostAssociations.User, PostAssociations.CommentsUser };
return service.Find(1, associations);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.