如何使 C# 对枚举类型使用 int 方法重载?

How to make C# use int method overload for enum types?

我在 C# 中得到了一个 class,它对不同的参数类型有多个重载:

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;
  }
}

现在我想为一行中的多个变量调用WriteRead,其中一个是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/ReadWriter/ReaderMyEnum 以便 w.Write(e) 会自动解决 Writer.Write(int) 更重要的是 r.Read(out e)Reader.Read(int)?

使用 where 约束:

public void Get<T>(out T value) where T : class, IInterface, new()

您明确表示 T 必须是引用类型(不是值类型,如枚举)。尝试删除 class 约束。

[编辑] 你也可以试试这个,避免 param:

  public T Get<T>() where T : new()
  {
    return default(T);
  } 

并将其命名为

c.Get<MyEnum>();

但同样,如果添加 IInterface 约束,则没有 Enum 可以满足它。

从对我的问题的评论和 Gian Paolo 的回答中,很明显 - 与 VB.NET 相反 - C# 不支持从 enumint 的隐式类型转换或反之亦然,即使使用技巧。

因此,我想要的 "one-method handles all enum types" 解决方案无法实现。

如果您不能(项目层次结构)或不想将每个枚举类型的重载添加到 Writer/Reader class 本身,您可以为枚举创建扩展方法类型。

回答有点晚,但由于我遇到了同样的问题,像这样的重载应该可以工作

public void Foo(int a)
{
    // do something
}

public void Foo(Enum @enum)
{
    Foo(Convert.ToInt32(@enum));
}