问题描述
作为练习的一部分,我试图为泛型类定义与特定类型一起使用时的特定行为。更确切地说,我想知道是否可以为泛型类型定义显式转换运算符,即从 list< T>
到 int []
As part of an exercise I am trying to define a specific behavior for a generic class when used with a specific type. More precisely, I was wondering if it is possible to define a explicit casting operator for a generic type, i.e. from list<T>
to int[]
不,我知道我可以简单地定义一个可以完成工作的方法,但这不是练习的目的。
No, I know I could simply define a method that does the work, however this is not the goal of the exercise.
假设通用类 list< T>
我试图定义以下显式转换方法
Assuming the generic class list<T>
I was trying to define the following explicit casting method
class list<T> {
...
public static explicit operator int[](list<T> _t) where T : System.Int32
{
// code handling conversion from list<int> to int[]
}
}
但这是行不通的。有什么想法可以使编译器吞并这个?
This doesn't work however. Any ideas on how to make the compiler swallow this?
推荐答案
首先,请更改名称遵循.NET约定和的类,避免与 List< T>
冲突。
Firstly, please change the name of the class to follow .NET conventions and avoid clashing 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.
这篇关于在C#中定义泛型的显式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!