ジェネリック型を固定型にキャストしようとしています。
以下は私が期待する動作ですが、根本的な欠陥があります。
public class Wrapper<T>
{
public T Value;
static public implicit operator TypeWithInt(Wrapper<int> wrapper)
{
return new TypeWithInt(wrapper.Value);
}
static public implicit operator TypeWithFloat(Wrapper<float> wrapper)
{
return new TypeWithFloat(wrapper.Value);
}
static public implicit operator TypeWithDouble(Wrapper<double> wrapper)
{
return new TypeWithDouble(wrapper.Value);
}
}
上記のコードは、次のエラーでコンパイルされません。
User-defined conversion must convert to or from the enclosing type
As Wrapper<int>
is different from Wrapper<T>
it'll never work, becauseWrapper<int>
は囲み型ではないため.
私の質問は次のとおりです。このキャスティングを機能させるにはどうすればよいですか? 方法はありますか?