[英]Implicit/Explicit casting operator from/to generic type
I'm trying to cast a generic type to a fixed one. 我正在尝试将通用类型转换为固定类型。
The following is what I expect to work, but there is a fundamental flaw in it. 以下是我期望的工作,但是其中有一个根本缺陷。
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);
}
}
The above code doesn't compile with the following error: 上面的代码无法编译并出现以下错误:
User-defined conversion must convert to or from the enclosing type
As Wrapper<int>
is different from Wrapper<T>
it'll never work, because Wrapper<int>
isn't the enclosing type. 由于
Wrapper<int>
与Wrapper<T>
不同,因此它将永远无法工作,因为Wrapper<int>
不是封闭类型。
So my question is: How can I make this casting work? 所以我的问题是: 如何使这种铸造工作? Is there a way?
有办法吗?
Your object model is a bit nonsensical because the .NET type system only considers at most 2 types at a time: 您的对象模型有点荒谬,因为.NET类型系统一次最多只考虑两种类型:
/* type 1 (int) */ int a = "abc" /* type 2 (string) */;
Yet you're trying to force another type in the middle which doesn't mesh. 但是,您试图在中间强制使用另一种不会啮合的类型。 This isn't a limitation of the type conversion process, but instead, a limitation of the language.
这不是类型转换过程的限制,而是语言的限制。 Every assignment (the phase at which implicit type conversions are enforced) can have at most 2 active parties, the left (
int
in the example above) and the right ( string
in the example above). 每个分配(强制执行隐式类型转换的阶段)最多可以有2个活动方,左边(在上面的示例中为
int
)和右边(在上面的示例中为string
)。 Cascading implicit casts are not supported and would likely be really hard to code for. 级联的隐式强制转换不受支持,可能很难编写。
The only possible solution I see to your problem would be to make this transition more visible to your user and add ToInt
, ToFloat
methods on Wrapper<T>
to allow it to do its job. 对于您的问题,我看到的唯一可能的解决方案是使此转换对您的用户更可见,并在
Wrapper<T>
上添加ToInt
和ToFloat
方法以使其完成工作。
Another point of interest might be the performance impact for doing this... the net result of your proposed wrapper is a boxing operation which may lead to unfortunate performance if you're working with a fair load. 另一个令人感兴趣的地方可能是这样做的性能影响...建议的包装程序的最终结果是装箱操作,如果您在中等负载下工作可能会导致不幸的性能。 The alternative would be to rearchitect your application to be less type specific.
替代方法是重新构造应用程序,使其不具有特定于类型的内容。 Doing so would likely also eliminate the issue you're currently facing.
这样做还可以消除您当前面临的问题。
您可以将强制类型转换添加到抽象的非泛型基类中,并使泛型类继承它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.