且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中定义泛型的显式转换

更新时间:2022-12-15 12:46:16

首先,更改名称遵循.NET约定的类,避免与 List< T> 冲突。

Firstly, please change the name of the class to follow .NET conventions and avoid ***ing with List<T>.

因此,您基本上无法做您想做的事情。您可以定义一个对 all T 有效的转换,然后针对不同的情况采取不同的措施。因此,您可以这样写:

With that out of the way, you basically can't do what you're trying to do. You can define a conversion which is valid for all T, and then take different action for different cases. So you could write:

public static explicit operator T[](CustomList<T> input)

然后如果 T int则区别对待。进行最后一部分并不是很好,但是如果您确实想要的话也可以这样做。

and then treat this differently if T is int. It wouldn't be nice to do the last part, but you could do it if you really wanted.

特定泛型类型上可用的成员是相同的,无论类型参数(在类型参数声明时声明的约束内)-否则它不是真正的泛型。

The members available on a particular generic type are the same whatever the type arguments (within the constraints declared at the point of type parameter declaration) - otherwise it's not really generic.

作为替代方案,您可以在顶部定义扩展方法级别的静态非一般类型:

As an alternative, you could define an extension method in a top-level static non-generic type elsewhere:

public static int[] ToInt32Array(this CustomList<int> input)
{
    ...
}

这将允许您编写:

CustomList<int> list = new CustomList<int>();
int[] array = list.ToInt32Array();

我个人还是觉得它比显式转换运算符更清楚。

Personally I'd find that clearer than an explicit conversion operator anyway.