繁体   English   中英

在 C# 中将泛型显式转换为另一种类型

[英]Explicit Casting Generic to Another Type in C#

我有以下 C++ 代码,在一个表示点的模板化类中。 我想把它翻译成 C#:

template <class T>
class Point
{
    public:
        T x;
        T y;
        T z;

    template<typename U> explicit Point(const Point<U> &p)
       : x((T)p.x), y((T)p.y), z((T)p.z)
    {
    }
}

此代码允许将给定类型的点显式转换为另一种类型的点。 例如,您可以使用它类似的东西(不可否认,我对这里的语法不是 100% 确定,但我明白了这个概念):

Point<float> p;
Point<int> q = (Point<int>)p;

如何在 C# 中启用与此等效的功能? 到目前为止,我有:

public class Point<T>
{
    public T X { get; set; }
    public T Y { get; set; }
    public T Z { get; set; }

    // Constructors exist that accept X, Y, and Z as parameters

    public static explicit operator Point<U>(Point<T> p)
    {

    }
}

但是,这会产生错误,说“U”未定义。 这是有道理的......但是我如何/在哪里定义U? 我的方法不正确吗?

我的问题和这里的问题之间的区别在于,我只是通过强制转换来更改泛型类的底层类型……而不是试图将一个泛型类更改为具有相同底层类型的不同泛型类。

我认为你能得到的最好的是:

public class Point<T>
{
    public T X { get; set; }
    public T Y { get; set; }
    public T Z { get; set; }

    public Point<U> As<U>()
    {
        return new Point<U>()
        {
            X = Convert<U>(X),
            Y = Convert<U>(Y),
            Z = Convert<U>(Z)
        };
    }

    static U Convert<U>(T t) => (U)System.Convert.ChangeType(t, typeof(U));
}

您无法定义泛型转换运算符,因此您需要将其作为显式函数。 此外,简单的强制转换(U)t不起作用,因此您需要Convert.ChangeType (如果您的类型是数字,它会起作用)。

用法:

var p1 = new Point<int> { X = 1, Y = 2, Z = 3 };
var p2 = p1.As<double>();

按预期工作)。

据我所知,只有在TU之间存在某种继承关系时,才允许在 C# 中使用这种泛型转换。

最接近的等价物是为转换定义一个通用方法:

public Point<U> To<U>()
{
    dynamic p = this;

    return new Point<U>((U)p.X, (U)p.Y, (U)p.Z);
}

您不能直接将T转换为U因为编译器无法知道它是否安全。 我使用dynamic关键字绕过该限制。

类似于凯文的回答,但没有dynamic是使用双重演员:

public Point<U> To<U>()
{
    return new Point<U>((U)(object)X, (U)(object)Y, (U)(object)Z);
}

我们的两个答案在编译时都没有发现任何问题。

您不能使用额外的泛型类型参数声明运算符,但您可以向或来自特定泛型类型(如Point<int>声明运算符。 C# 也不会让您通过从或到T进行任意转换来执行任意转换。

保持少量类型安全的最少样板重选项是将T参数限制为IConvertible

public class Point<T> where T : IConvertible
{
    // ...

    public static explicit operator Point<int>(Point<T> point)
    {
        // The IFormatProvider parameter has no effect on purely numeric conversions
        return new Point<int>(point.X.ToInt32(null), point.Y.ToInt32(null), point.Y.ToInt32(null));
    }    
}

但是,这不会阻止用户声明无意义的、不受支持的类型,例如Point<DateTime> ,然后在尝试转换时会在运行时抛出。

你不能定义额外的泛型类型约束,但你可以使用运算符和方法来做这样的事情。

public class Point<T>
{
    public T X { get; set; }
    public T Y { get; set; }
    public T Z { get; set; }

    public static explicit operator Point<T>(Point<int> v)
    {
        return v.As<T>();
    }

    public static explicit operator Point<T>(Point<double> v)
    {
        return v.As<T>();
    }

    public static explicit operator Point<T>(Point<float> v)
    {
        return v.As<T>();
    }

    public Point<TU> As<TU>()
    {
        return new Point<TU>()
        {
            X = ConvertTo<TU>(X),
            Y = ConvertTo<TU>(Y),
            Z = ConvertTo<TU>(Z)
        };
    }

    private static TU ConvertTo<TU>(T t)
    {
        return (TU) Convert.ChangeType(t, typeof(TU));
    }
}

用法:

        Point<double> d = new Point<double>()
        {
            X = 10d, Y = 10d, Z = 10d
        };

        Point<int> i = (Point<int>) d;

        Point<float> f = (Point<float>) i;

        d = (Point<double>) f;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM