Вся кодовая база здесь (немного старая версия без конкретной проблемы). < /P>
Вот проблематичный код: < /p>
Код: Выделить всё
public static T GetUserInput(
string message,
bool acceptEmpty = false,
bool acceptWhitespaceOnly = false,
uint? expectedLength = null,
T? defaultValue = null)
{
if (!message.EndsWith(" "))
{
message += " ";
}
if (defaultValue is not null)
{
message += $"[Default: {defaultValue}] ";
}
while (true)
{
Console.Write(message);
string? input = Console.ReadLine();
if (input == null)
{
Console.WriteLine("Input cannot be null. Please make a valid input.");
continue;
}
// If input is empty/whitespace and default is available
if (string.IsNullOrWhiteSpace(input))
{
if (string.IsNullOrEmpty(input))
{
if (defaultValue is not null)
return defaultValue;
if (!acceptEmpty)
{
Console.WriteLine("Input cannot be empty. Please make a valid input.");
continue;
}
}
else // input is whitespace but not empty
{
if (!acceptWhitespaceOnly)
{
Console.WriteLine("Input cannot be whitespace only. Please make a valid input.");
continue;
}
}
}
if (expectedLength != null && input!.Length != expectedLength)
{
Console.WriteLine($"Input must be {expectedLength} characters long. Please make a valid input.");
continue;
}
switch (typeof(T))
{
case Type t when t == typeof(string):
return (T)(object)input!;
case Type t when t == typeof(int):
if (int.TryParse(input, out int intResult))
return (T)(object)intResult;
Console.WriteLine("Invalid input. Please enter a valid whole number.");
break;
case Type t when t == typeof(double):
if (double.TryParse(input, out double doubleResult))
return (T)(object)doubleResult;
Console.WriteLine("Invalid input. Please enter a valid number.");
break;
case Type t when t == typeof(bool):
if (bool.TryParse(input, out bool boolResult))
return (T)(object)boolResult;
Console.WriteLine("Invalid input. Please enter 'true' or 'false'.");
break;
case Type t when t.IsEnum:
if (Enum.TryParse(typeof(T), input, ignoreCase: true, out object? enumResult))
return (T)enumResult;
Console.WriteLine($"Invalid input. Please enter one of the following: {string.Join(", ", Enum.GetNames(typeof(T)))}.");
break;
default:
throw new NotSupportedException($"Type {typeof(T)} is not supported.");
}
}
}
< /code>
Единственная часть, которая, по-видимому, сталкивается с проблемами,-это фактическая подпись метода: < /p>
static T GetUserInput(
string message,
bool acceptEmpty = false,
bool acceptWhitespaceOnly = false,
uint? expectedLength = null,
T? _defaultValue_ = null)
cs1750: значение типа '' не может использоваться в качестве параметра невыполнения, потому что нет стандартных конвертиров /> < /blockquote>
Цель кода состоит в том, чтобы принять пользовательский ввод в CLI и оптимизировать процесс сбора указанного ввода пользователя в остальной части программы.
Код: Выделить всё
string name = GetUserInput("What is your name? ");
int age = GetUserInput("How old are you? ");
bool displayInformation = GetUserInput("Display name and age? ");
< /code>
Ранее это сработало.string plaintext = GetUserInput("What would you like to encode? [Default: \"Hello\"]");
< /code>
и пользователь может либо заполнить нужную строку, либо нажать Enter (ничего не набирая), чтобы вернуться к значению по умолчанию, указанному при вызове функции, т.е.GetUserInput(message, defaultValue: "Hello")
< /code>
На данный момент код просто не будет компилироваться.static T? GetUserInput()
Первоначально, вместо того, чтобы иметь defaultValue null , я установил, что он установил для default .
, к сожалению, что дало бы ему значение по умолчанию, определяемое между code> . Ввод для логического: < /p>
Код: Выделить всё
GetUserInput("true or false?");
Код: Выделить всё
public static T? GetUserInput(
string message,
bool acceptEmpty = false,
bool acceptWhitespaceOnly = false,
uint? expectedLength = null,
T? defaultValue = null) where T : class
< /code>
и для типов значений < /p>
public static T? GetUserInput(
string message,
bool acceptEmpty = false,
bool acceptWhitespaceOnly = false,
uint? expectedLength = null,
T? defaultValue = null) where T : struct
Подробнее здесь: https://stackoverflow.com/questions/796 ... ovided-one