[英]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.