gpt4 book ai didi

C# 转换泛型类型(如 C++ 用户定义的转换)

转载 作者:行者123 更新时间:2023-11-30 15:26:44 25 4
gpt4 key购买 nike

C# 中有没有一种方法可以为泛型类型执行用户定义的转换?

例如:

class Stack<T> 
{
private T x; //should be an array but doesn't matter for this example

public Stack(T input)
{
x = input;
}

public Stack<Q> Convert<Q>(Stack<T> inputStack)
{
//what would go here ? The call is below.
}
}

//main code
Stack<int> stack = new Stack<int>(2);
Stack<long> longstack = stack.Convert<long>(stack);

我想编译器可以在 Convert 函数中推断出 Q 是 long 而 T 是 int,但它似乎不起作用。

最佳答案

不,因为类级泛型类型参数无法从用法中自动推断出来。

I would imagine that the compiler can deduce that Q is long and T is int in the Convert function, but it doesn't seem to work.

也许吧,但归根结底,泛型类型参数不属于构造函数。也就是说,您根据什么构造函数参数/参数为类型提供通用参数?如果不止一个构造函数参数会怎样?

public class A<T>
{
// Which one should be used to auto-infer T from usage?
// Maybe the integer? Or the bool? Or just the string...?
// Every choice seems a joke, because it would be absolutely
// arbitrary and unpredictable...
public A(int x, string y, bool z)
{
}
}

现在以您的示例代码为例。它有同样的问题:应该从您的 Convert 静态方法中使用什么参数来从用法中推断泛型类型参数?如果 Convert 有多个参数...会怎样?

关于C# 转换泛型类型(如 C++ 用户定义的转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28793026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com