我四處搜尋,但沒有找到做任何的例子,雖然這是有幫助的:通用T搭配枚舉和鑄造噸至ENUM
Create Generic method constraining T to an Enum
我有在包裝功能的通用功能API(我無法觸及)。包裝函數需要一個System.Enum並返回相同的值。我的通用版本在這個例子的非剝離版本中簡化了很多事情。
問題是,我不能從T到System.Enum,或者返回,因爲T不限於System.Enum(至少這是我的理解)。
下面的代碼工作,但我很好奇,想知道是否有任何隱藏的陷阱,或者更好的辦法,因爲我是很新的仿製藥:
using System
using System.Collections.Generic
...
public T EnumWrapper<T>(T enumVar) where T : struct, IFormattable, IConvertible, IComparable
{
if (!typeof(T).IsEnum)
throw new ArgumentException("Generic Type must be a System.Enum")
// Use string parsing to get to an Enum and back out again
Enum e = (Enum)Enum.Parse(typeof(T), enumVar.ToString());
e = WrappedFunction(e);
return (T)Enum.Parse(typeof(T), e.ToString());
}
如果這是確定的,然後讓這個作爲一個例子。我找不到這個,至少這是一個有效的解決方法。
P.S.在這種情況下,性能不是問題。我以爲我在想字符串工作可能會很慢,我總是對性能技巧感興趣。
新增IFormattable和IComparable(謝謝@Michael B): http://stackoverflow.com/questions/7508455/generic-t-with-enum-and-casting-t-to-enum/7516220#7516220 – Rafe