正如@fredrik和@Henk Holterman所说,这个功能并不是内置在语言中的。但是...(这里有一个大但是)我们是程序员!!我们几乎能够自己实现任何东西!
在解释之前,让我们先看一下代码,因为很多时候代码可以自我解释:
public class Reader
{
public Reader Read<T>(out T t) where T : struct
{
var line = Console.ReadLine();
t = GetValueFromStringRepresentation<T>(line);
return this;
}
public Reader Read(out string str)
{
str = Console.ReadLine();
return this;
}
}
我们在这里实现了方法链模式,以便可以根据需要多次阅读,并使用
out参数来初始化我们的变量。此实现仅适用于结构体(但不是全部...)和字符串,这就是为什么有重载方法接受字符串的原因... C#不允许在类型参数约束中指定AND... =(
下一步是解析字符串值,以下是我如何做到的... 保持友好...这只是演示代码:
private static T GetValueFromStringRepresentation<T>(string str)
{
var type = typeof(T);
var value = type == typeof(string)
? str
: type == typeof(bool)
? bool.Parse(str)
: type == typeof(sbyte)
? sbyte.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(byte)
? byte.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(short)
? short.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(ushort)
? ushort.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(int)
? int.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(uint)
? uint.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(long)
? long.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(char)
? char.Parse(str)
: type == typeof(float)
? float.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(double)
? double.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(ulong)
? ulong.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(decimal)
? decimal
.Parse(str, CultureInfo.InvariantCulture)
: type == typeof(Guid)
? Guid.Parse(str)
: (object)null;
return (T)value;
}
如我之前所说,这种方法不能直接适用于所有可能的结构体,但您可以轻松添加一个可选参数来封装解析,例如: Func< string, T > parser。
进行测试:
int a, b;
string c;
char d;
var reader = new Reader();
reader.Read(out a)
.Read(out b)
.Read(out c)
.Read(out d);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.ReadLine();
编辑
如果您正在使用C# 7+,您可以利用内联变量声明:
var reader = new Reader();
reader.Read(out int a)
.Read(out int b)
.Read(out string c)
.Read(out char d);