如何在隐式运算符中使用泛型?

时间:2009-04-24 06:22:01

标签: c# generics operator-overloading

我有一个非常简单的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; 
        }
    }

2 个答案:

答案 0 :(得分:2)

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

下一个问题是“如何从T2转到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>

答案 1 :(得分: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));
    }
}