简体   繁体   English

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

[英]Defining explicit casting for generic types in C#

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, ie from list<T> to int[] 更确切地说,我想知道是否可以为泛型类型定义显式转换运算符,即从list<T>int[]

No, I know I could simply define a method that does the work, however this is not the goal of the exercise. 不,我知道我可以简单地定义一种可以完成工作的方法,但这不是练习的目的。

Assuming the generic class list<T> I was trying to define the following explicit casting method 假设通用类list<T>我试图定义以下显式转换方法

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? 关于如何使编译器可以解决这个问题的任何想法?

Firstly, please change the name of the class to follow .NET conventions and avoid clashing with List<T> . 首先, 更改类的名称以遵循.NET约定, 避免与List<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. 可以定义一个对所有 T有效的转换,然后针对不同的情况采取不同的操作。 So you could write: 所以你可以这样写:

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

and then treat this differently if T is int . 如果Tint ,则将其区别对待。 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)
{
    ...
}

That would allow you to write: 那可以让你写:

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

Personally I'd find that clearer than an explicit conversion operator anyway. 无论如何,我个人都会发现它比显式转换运算符更清晰。

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

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