隐式解析抽象参数的正确 class

Implicitly resolve the correct class for an abstract argument

给定以下代码:

static class StaticClass
{
  public static void DoSomething(BaseClass Value)
  {
  }
}

abstract class BaseClass
{
}

class DerivedClassForString : BaseClass
{
  public string Value { get; }

  public DerivedClassForString(string Value)
  {
    this.Value = Value;
  }

  public static implicit operator DerivedClassForString(string Value)
  {
    return new DerivedClassForString(Value);
  }
}

class DerivedClassForInt32 : BaseClass
{
  public int Value { get; }

  public DerivedClassForInt32(int Value)
  {
    this.Value = Value;
  }

  public static implicit operator DerivedClassForInt32(int Value)
  {
    return new DerivedClassForInt32(Value);
  }
}

我希望能够做到以下几点:

StaticClass.DoSomething("Hello world!"); //This should create an instance of DerivedClassForString
StaticClass.DoSomething(16); //This should create an instance of DerivedClassForInt32

但这不起作用。

有什么方法可以提示编译器通过派生的 类 并搜索隐式解析器?

根据 StaticClass.DoSomethingBaseClass 的实际作用,您可以使 BaseClassStaticClass.DoSomething 通用:

static class StaticClass
{
    public static void DoSomething<T>(BaseClass<T> Value)
    {
    }
}

class BaseClass<T>
{
    public T Value { get; }

    public BaseClass(T Value)
    {
      this.Value = Value;
    }

    public static implicit operator BaseClass<T>(T Value)
    {
        return new BaseClass<T>(Value);
    }
}

如果您希望编译器在调用 StaticClass.DoSomething 时推断出 T,您需要使 DoSomething 看起来像这样:

static class StaticClass
{
    public static void DoSomething<T>(T Value)
    {
        BaseClass<T> realValue = Value;
    }
}

另一种方法是在 BaseClass 本身内定义隐式转换:

abstract class BaseClass
{
    public static implicit operator BaseClass(string Value)
    {
        return new DerivedClassForString(Value);
    }

    public static implicit operator BaseClass(int Value)
    {
        return new DerivedClassForInt32(Value);
    }
}