如何在隐式运算符中使用泛型?
我有一个非常简单的 C++ 类:
struct Pt_t
{
T x, y;
template <class T2> operator Pt_t<T2>() { Pt_t<T2> pt = {x, y}; return pt; }
};
它允许我创建一个具有 T 作为我想要的任何类型的 pt。 我也可以Pt_t
没有问题。 我如何在 C# 中做同样的事情? 我尝试了以下方法并收到错误:
class Pt<T>
{
public T x, y;
//between operator and <T2>, error CS1031: Type expected
public static implicit operator<T2> Pt<T>(Pt<T2> v) {
Pt<T> r = new Pt<T>();
r.x = v.x;
r.y = v.y;
return r;
}
}
I have a c++ class that is very simple:
struct Pt_t
{
T x, y;
template <class T2> operator Pt_t<T2>() { Pt_t<T2> pt = {x, y}; return pt; }
};
That allows me to create a pt that has T as any type I want. I can also do Pt_t<s8> = Pt_t<u64>;
without a problem. How do I do the same in C#? I tried the below and got an error:
class Pt<T>
{
public T x, y;
//between operator and <T2>, error CS1031: Type expected
public static implicit operator<T2> Pt<T>(Pt<T2> v) {
Pt<T> r = new Pt<T>();
r.x = v.x;
r.y = v.y;
return r;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,我认为这是不可能的。 您可能需要添加一个方法,例如
To
。下一个问题将是“如何从
T2
到T
- 你不能只分配它们。一个选项可能是转换委托:No, I don't think that is possible. You may have to add a method, such as
To<T>
.The next problem will be "how to get from
T2
toT
- you can't just assign them. One option might be a conversion delegate:您可以使用 Nemerle: ( http://github.com/rsdn/nemerle ) :
输出:
Reflector代码:
You can use Nemerle: ( http://github.com/rsdn/nemerle ) :
Output:
Reflector for code: