'T' is a type parameter, which is not valid in the given context
Попытался использовать дженерики в методе, но получаю ошибку из заголовка, полагаю, компилятору не нравится, что метод TryParse может быть не объявлен для типа Т. Как можно исправить ошибку?
Полный код:
using System;
using System.IO;
public class Program
{
public static T[] ArrayInput<T>() {
int n;
bool IsInt;
do {
Console.Write("Enter array's size: ");
IsInt = int.TryParse(Console.ReadLine(), out n);
} while (!IsInt);
T [] array = new T[n];
for (int i = 0; i < n; ++i) {
bool IsT;
do {
Console.Write("Enter {i + 1} member of array: ");
IsT = T.TryParse(Console.ReadLine(), out n); // ошибка
} while (!IsT);
}
return array;
}
public static T[] SelectionSort<T>(T[] array) {
for (int i = 0; i < array.Length - 1; i++)
{
int min = i;
for (int j = i + 1; j < array.Length; j++)
{
if (array[j] < array[min]) // ошибка при сравнении
{
min = j;
}
}
T dummy = array[i];
array[i] = array[min];
array[min] = dummy;
}
return array;
}
public static void PrintArray<T>(string name_of_array, T[] array) {
Console.Write(name_of_array);
foreach (T member in array)
{
Console.Write(' ');
Console.Write(member);
}
Console.WriteLine();
}
public static void Main()
{
short[] unsorted_short_array = ArrayInput<short>();
double[] unsorted_double_array = ArrayInput<double>();
short[] sorted_short_array = SelectionSort<short>(unsorted_short_array);
double[] sorted_double_array = SelectionSort<double>(unsorted_double_array);
PrintArray<short>("Unsorted array of shorts:", unsorted_short_array);
PrintArray<short>("Sorted array of shorts:", sorted_short_array);
PrintArray<double>("Unsorted array of doubles:", unsorted_double_array);
PrintArray<double>("Sorted array of doubles:", sorted_double_array);
}
}
Ответы (2 шт):
Автор решения: VladD
→ Ссылка
Если вы хотите поддерживать числовые типы, то должно сработать так:
for (int i = 0; i < n; ++i)
{
Console.Write($"Enter {i + 1} member of array: ");
while (true)
{
try
{
var input = Console.ReadLine();
array[i] = (T)Convert.ChangeType(input, typeof(T));
break;
}
catch (Exception)
{
Console.Write("Wrong input, try again: ");
}
}
}
К сожалению, на текущий момент нету возможности сделать generic constraint на числовые типы. Но он планируется в будущем.
Автор решения: aepot
→ Ссылка
Как выше замечено, TypeDescriptor - полезная штука. Я добавил ограничение на IConvertible, чтобы случайно непреобразуемый тип не подставить.
public static T[] ArrayInput<T>() where T : struct, IConvertible
{
int n;
do
{
Console.Write("Enter array's size: ");
} while (!int.TryParse(Console.ReadLine(), out n) || n <= 0);
T[] array = new T[n];
var converter = TypeDescriptor.GetConverter(typeof(T));
for (int i = 0; i < n; ++i)
{
while(true)
{
Console.Write($"Enter {i + 1} member of array: ");
string input = Console.ReadLine();
if (converter.IsValid(input))
{
array[i] = (T)converter.ConvertFromString(input);
break;
}
}
}
return array;
}