在 C# 中是否可以通过以下方式重载通用强制转换运算符?
只是想知道是否有办法在 C# 3.5 中表示以下代码:
public struct Foo<T> {
public Foo(T item) {
this.Item = item;
}
public T Item { get; set; }
public static explicit operator Foo<U> ( Foo<T> a )
where U : T {
return new Foo<U>((U)a.Item)
}
}
谢谢
Just wondering if there is anyway to represent the following code in C# 3.5:
public struct Foo<T> {
public Foo(T item) {
this.Item = item;
}
public T Item { get; set; }
public static explicit operator Foo<U> ( Foo<T> a )
where U : T {
return new Foo<U>((U)a.Item)
}
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
转换运算符不能是通用的。 根据规范第 10.10 节,以下是转换运算符声明符的格式:
将此与方法头进行比较:
(对格式感到抱歉 - 不知道如何做得更好。)
请注意,运算符格式不包含类型参数列表或类型参数约束。
Conversion operators can't be generic. From the spec section 10.10, here's the format of a conversion-operator-declarator:
Compare this with, say, a method-header:
(Sorry about the formatting - not sure how to do it better.)
Note that the operator format doesn't include a type parameter list or type parameter constraints.
您的代码归结为以下行:
return new Foo((U)a.Item)
您尝试将基类分配给继承的类,这是不可能的。
假设 T(基类)的类型为 Stream,U 的类型为 MemoryStream(继承类),您不能将 Stream 分配给
MemoryStream
类型的变量。Your code boils down to the line:
return new Foo<U>((U)a.Item)
Where you try to assign a baseclass to an inherited class, which is impossible.
Let's say T (base-class) is of type
Stream
and U is of typeMemoryStream
(inherited class), you cannot assign aStream
to a variable of typeMemoryStream
.我认为简短的答案是“不可能。尝试使用一种方法代替”
也似乎是这个问题的欺骗
.NET 泛型中重载运算符约束的解决方案
I think the short answer is "Not possible. Try using a method instead"
Also seems to be dupe of this question
Solution for overloaded operator constraint in .NET generics