4

我有一个非常简单的 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<s8> = Pt_t<u64>;没有问题。我如何在 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; 
        }
    }
4

2 回答 2

2

不,我不认为这是可能的。您可能需要添加一个方法,例如To<T>.

下一个问题将是“如何从T2to T- 你不能只分配它们。一个选项可能是转换委托:

public Pt<TDestination> To<TDestination>(
    Converter<T, TDestination> converter)
{
    if (converter == null) throw new ArgumentNullException("converter");
    Pt<TDestination> t = new Pt<TDestination>();
    t.x = converter(x);
    t.y = converter(y);
    return t;
}
...
var p = new Pt<int> { x = 1, y = 2 };
var p2 = p.To(t => t.ToString()); // a Pt<string>
于 2009-04-24T06:40:59.210 回答
0

您可以使用 Nemerle:(http://github.com/rsdn/nemerle):

using System.Console;

class A[T]
{
    public static @:[From](x : A[From]) : A[T]
    {
      A()
    }
}


class Base{}
class Derived{}


def a = A.[Derived]();
def b : A[Base] = a;

WriteLine($"$a $b");

输出:

A`1[Derived] A`1[Base]

代码反射器:

internal class A<T>
{
    public static implicit operator A<T><From>(A<From> x)
    {
        return new A<T>();
    }
}

public class a
{
    public static void Main()
    {
        A<Derived> a = new A<Derived>();
        A<Base> a2 = (A<Base>) a;
        Console.WriteLine(Convert.ToString(a) + " " + Convert.ToString(a2));
    }
}
于 2011-03-08T16:09:43.430 回答