[英]How to make C# use int method overload for enum types?
我在 C# 中有一個類,它具有針對不同參數類型的多個重載:
class Writer
{
public Writer Write(bool value)
{
// Do something with value
return this;
}
public Writer Write(double value)
{
// Do something with value
return this;
}
public Writer Write(int value)
{
// Do something with value
return this;
}
public Writer Write<T>(T value) where T : class, IInterface, new()
{
// Do something with value
return this;
}
}
class Reader
{
public Reader Read(out bool value)
{
// Retrieve value
return this;
}
public Reader Read(out double value)
{
// Retrieve value
return this;
}
public Reader Read(out int value)
{
// Retrieve value
return this;
}
public Reader Read<T>(out T value) where T : class, IInterface, new()
{
// value = new T() or null
return this;
}
}
現在我想為一行中的多個變量調用Write
和Read
,其中一個是enum
類型。 但是,該枚舉類型導致方法解析困難。 (順便說一句:我習慣於 VB.NET,其中Enum
類型與Integer
參數兼容。)
enum MyEnum : int
{
Foo = 0, Bar = 1
}
class CallingClass
{
public void Call()
{
bool b;
double d;
int i;
IInterface o;
MyEnum e = MyEnum.Foo;
var w = new Writer();
// Unintuitive for Write
w
.Write(b)
.Write(d)
.Write(i)
.Write(o)
.Write((int) e);
// w.Write(e); // resolves to Writer.Write<T>(T)
// => Compile error: "MyEnum has to be reference type to match T"
// Even worse for Read, you need a temp variable
// and can't use fluent code anymore:
var r = new Reader();
r
.Read(out b)
.Read(out d)
.Read(out i)
.Read(out o);
int tmp;
r.Read(out tmp);
e = (MyEnum) tmp;
}
}
有沒有什么辦法可以修改Write
/ Read
, Writer
/ Reader
或MyEnum
使w.Write(e)
將自動解析到Writer.Write(int)
更重要的r.Read(out e)
以Reader.Read(int)
?
答案有點晚,但由於我遇到了同樣的問題,所以像這樣的超載應該有效
public void Foo(int a)
{
// do something
}
public void Foo(Enum @enum)
{
Foo(Convert.ToInt32(@enum));
}
使用 where 約束:
public void Get<T>(out T value) where T : class, IInterface, new()
您明確說 T 必須是引用類型(而不是枚舉類型的值類型)。 嘗試刪除類約束。
[編輯] 你也可以試試這個,避免參數:
public T Get<T>() where T : new()
{
return default(T);
}
並將其稱為
c.Get<MyEnum>();
但同樣,如果您添加 IInterface 約束,則沒有 Enum 可以滿足它。
從對我的問題的評論和 Gian Paolo 的回答來看,很明顯 - 與 VB.NET 相對 - C# 不支持enum
到int
隱式類型轉換,反之亦然,即使使用技巧也是如此。
因此,我想要的“一種方法處理所有枚舉類型”的解決方案是不可能實現的。
如果您不能(項目層次結構)或不想將每個枚舉類型的重載添加到Writer
/ Reader
類本身,您可以為枚舉類型創建擴展方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.