我正在使用自己的自定义堆栈类,并且我正在尝试创建一个通用方法来创建新堆栈(通用对象)。我经常使用 int 类型的堆栈,只是偶尔需要其他类型。我可以将 T 的默认类型设置为 int 吗?
方法如下:
public static Stack<T> newStack<T>(int length)
{
Stack<T> s = new Stack<T>();
for (int i = 0; i < length; i++)
{
Console.WriteLine("print num");
string input = Console.ReadLine();
T value = (T)Convert.ChangeType(input, typeof(T));
s.Push(value);
}
return s;
}
我想使用这样的方法:
newStack(5);//defult int type
以及任何其他类型
newStack<string>(5)
有人可以帮忙吗?谢谢。
最佳答案
您无法为 T 指定默认类型,但是您可以简单地重载 newStack
方法来获得您想要的行为。重载方法将自动创建一个int
类型的新堆栈。
你的代码看起来像这样:
public static Stack<T> newStack<T>(int length)
{
Stack<T> s = new Stack<T>();
for (int i = 0; i < length; i++)
{
Console.WriteLine("print num");
string input = Console.ReadLine();
T value = (T)Convert.ChangeType(input, typeof(T));
s.Push(value);
}
return s;
}
public static Stack<int> newStack(int length)
{
// Call our original new stack method but pass
// integer as the type T
return newStack<int>(length);
}
如果您只想创建一个新的整数类型堆栈,则可以调用第二个方法,如下所示:
newStack(5);
否则,您可以使用以下方法创建其他类型的堆栈:
newStack<string>(5);
关于c# - 如何在静态泛型方法中设置 T 的默认类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60148101/