我有一個枚舉每個成員DescriptionAttribute
。 因爲我無法通過WCF發送這個DescriptionAttribute
(我很難學會這一點),所以我一直試圖創建一個方法,向我發送一個描述字典。 有點掙扎左右,我想出了這個方法在我的WCF服務後:獲取枚舉說明以某種方式「一般」通過WCF
public IDictionary<Enum, string> GetEnumDescriptionsList(string enumtype)
{
Type t = Type.GetType(enumtype);
if (t.BaseType != typeof(Enum))
{
return null;
}
var returnvalue = new Dictionary<Enum, string>();
foreach (Enum value in Enum.GetValues(t))
{
returnvalue.Add(value, value.GetDescription());
}
return returnvalue;
}
的方法的調用:
var myDict = GetEnumDescriptionsList(typeof (UserType).ToString());
這工作得很好,當我打這通電話在與該方法相同的類中,但是當我通過WCF進行調用時,返回空值。 調試後我發現字符串參數包含一個「不正確的」值。我的意思是,其他客戶端上的UserType.ToString()
具有不同的名稱空間,然後是WCF服務中的名稱空間。
閱讀this post解釋了這個問題。
在這一刻我很卡住位置:泛型是不可能的,發送類型爲Type
類型的參數是不可能的(see this post),... 最後一個選擇是編寫每個枚舉的方法我有(現在9),但我覺得有一種比這更好的方式。
在此先感謝。
UPDATE: 使用由我具有以下一段代碼來創建字典@KeithS提供的解決方案:
Assembly asm = Assembly.GetExecutingAssembly();
foreach (Type type in asm.GetTypes())
{
if (type.IsEnum)
{
enumTypeNames.Add(type.Name, type.AssemblyQualifiedName);
}
}
在web服務的方法返回每enummember給定類型的字典:
public IDictionary<string, string> GetEnumDescriptionsList(string enumtypename)
{
var enumtypenames = EnumMethods.GetEnumTypeNames();
var returnvalue = new Dictionary<string, string>();
string fullyQualifiedTypeName;
enumtypenames.TryGetValue(enumtypename, out fullyQualifiedTypeName);
var enumType = Type.GetType(fullyQualifiedTypeName);
foreach (Enum value in Enum.GetValues(enumType))
{
returnvalue.Add(value.ToString(), value.GetDescription());
}
return returnvalue;
}
從客戶端調用:
var returnvalue = client.GetEnumDescriptionsList(typeof(UserType).Name);
個
工程就像一個魅力,除了這個問題我已經張貼在幾天前:Name of enum in innerclass changes through WCF-service
當我做從客戶端類似的電話:
var returnvalue = client.GetEnumDescriptionsList(typeof(ActionsMailDirectLinkContent).Name);
它給命名爲「ActionsMailDirectLinkContent
」但在我的enumtypes字典中,我有「MailDirectLinkContent
」。 所以我的問題是如果有一種方法可以避免這種情況,或者我必須將我的枚舉從Actions-class中僅作爲唯一的解決方案。
更新2: 正如在他的評論@KeithS提到的,我不得不採取枚舉了我的班。我已經把它們放在一個子文件夾中,所以它們仍然是「分組」的,但上面的方法對所有的枚舉都是這樣工作的。
Thx Keith。
會的「所有可用的枚舉類型的枚舉」是可行的嗎? –
@Marc;我想提出這個建議,但是當添加一個Enum時,它肯定需要在多個地方更改代碼(因此必須知道你必須這樣做)。這是否是一件大事取決於超出問題範圍的各種事情。 – KeithS
@KeithS確實;它可能是很好的 - 它可能是完全不可行/不合適的 - 因此評論(問題)不是答案; p –