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



给定以下代码:

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

但是,这不起作用。

有没有办法给编译器一个提示,以浏览派生类并搜索隐式解析器?

另一种方法是定义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);
}
}

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

相关内容

  • 没有找到相关文章

最新更新