gpt4 book ai didi

c# - C# 中的 I/O 级联

转载 作者:太空狗 更新时间:2023-10-29 23:28:35 25 4
gpt4 key购买 nike

在 C++ 中,'>>' 和 '<<' 在执行输入/输出操作时用于级联。
有什么方法可以在 C# 中完成这些事情吗?到现在为止,我知道我可以一次接受一个输入并将其分配给一个变量,例如,在以下代码片段中:

int a,b;
Console.Write("Enter the value of first number: ");
a=Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the value of second number: ");
b=Convert.ToInt32(Console.ReadLine());

而在 C++ 中,可以做同样的事情:

int a,b;
cout<<"Enter the values of the two numbers: ";
cin>>a>>b;

最佳答案

正如@fredrik 和@Henk Holterman 所说,此功能并未内置到语言中。但是...(大但在这里)我们是程序员!几乎没有什么是我们自己无法实现的!

在解释之前让我们先看一下代码,因为很多时候代码可以 self 解释:

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;
}

//GetValueFromStringRepresentation stuff
}

我们在这里实现了一个方法链模式来根据需要多次读取,我们使用 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 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);

关于c# - C# 中的 I/O 级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50772764/

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