我想寫一個接受枚舉的通用類。由於該類旨在實現一些接口,主要目標是能夠將枚舉視爲實現這些接口的其他對象(例如用於列表擴展等)。因此,對於樣品枚舉枚舉的通用類 - 投射問題
public enum QEnum : int
{
xlNoValue = 0,
xlSomeValue = 1
}
public static class QEnumExtensions
{
public static string toString(this QEnum xThis)
{
...
}
public static QEnum toEnum(this string xThis)
{
...
}
}
我想聲明泛型類如
public class QEnumHolder<T> where T : struct, IConvertible
{
private T mxVal = default(T);
public QEnumHolder()
{
if (!typeof(T).IsEnum) throw new NotSupportedException();
}
public QEnumHolder(T xVal)
{
if (!typeof(T).IsEnum) throw new NotSupportedException();
mxVal = xVal;
}
static public implicit operator QEnumHolder<T>(T xVal)
{
return new QEnumHolder<T>(xVal);
}
static public implicit operator T(QEnumHolder<T> xVal)
{
return (T)xVal.mxVal;
}
public string toString()
{
if (mxVal is QEnum) return ((QEnum)Convert.ToInt32(mxVal)).toString();
...
}
public void fromString(string xString)
{
if (mxVal is QEnum)
mxVal = (???)xString.toEnum(); // problem
}
}
所有我們使用實現
- 的toString()函數返回的枚舉一個「漂亮」的字符串,可以進入comboBoxes等
- 將字符串轉換爲枚舉,如上
因此toString/toEnum的結構幾乎是給定的。問題是最後一行代碼行標有「問題」。我不知道如何告訴編譯器,在這個分支中,toEnum()
和T
的返回類型將是相同的。
我試圖通過宣佈mxVal
爲int
並在任何地方使用Convert.ToInt32
來解決此問題。然而,然後我碰到operator T
問題,其中編譯器反對將int
轉換爲T
(編譯器無法知道T
將枚舉,因此我不能使用任何「int to enum conversion」討論在這裏)。
作爲一般規則,C#使用駱駝案例d代表'ToString()'你應該重寫。 – Bauss
@Bauss:我知道,我只是不喜歡它。與Equals()等相同 - 如果你不覆蓋它,你會得到一個你不關心的實現,並且沒有人會通知你。 –
這個設計有很多問題。如果你的類包含像'QEnum'和'(QEnum)something''這樣的代碼,即** ** concrete **類型,那麼它不是**泛型類。另外,你不能有一個只有返回類型不同的多個'ToEnum(string)'擴展方法。 –