当输出变量为 a 时是否可以使用C#7 功能out variablesTuple?
我的具体场景是这样的:
private readonly Dictionary<int, (bool, DateTime)> _dictionary;
public void SomeMethod(int number)
{
if (this._dictionary.TryGetValue(number, out (bool isTrue, DateTime timestamp)) // what is the correct syntax?
// use isTrue and timestamp here
}
Run Code Online (Sandbox Code Playgroud)
如果这是可能的,我似乎找不到正确的语法。
澄清:我希望能够直接解构为isTrue而timestamp不是必须创建另一个变量。
Dwe*_*rly 12
考虑以下代码:
using System;
using System.Collections.Generic;
namespace ConsoleApp1 {
class Program {
private static Dictionary<int, (bool, DateTime)> _dictionary;
public static void SomeMethod(int number) {
if (_dictionary.TryGetValue(number, out (bool isTrue, DateTime timestamp) booltime)) {
Console.WriteLine($"Found it: {booltime.isTrue}, {booltime.timestamp}");
}
else {
Console.WriteLine($"{number} Not Found");
}
}
static void Main(string[] args) {
_dictionary = new Dictionary<int, (bool, DateTime)>();
_dictionary.Add(0, (true, DateTime.Now));
SomeMethod(1);
SomeMethod(0);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它将产生以下输出:
1 Not Found
Found it: True, 6/26/2018 4:56:59 PM
Run Code Online (Sandbox Code Playgroud)
您可以通过在调用参数中定义变量或定义所需类型的单独变量来获取元组作为输出参数。您还可以使用 var 关键字,如下所示:
if (_dictionary.TryGetValue(number, out var booltime)) {
Console.WriteLine($"Found it: {booltime.Item1}, {booltime.Item2}");
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果执行此操作,您将不会拥有命名元组属性,并且必须使用 Item1 和 Item2。
| 归档时间: |
|
| 查看次数: |
5053 次 |
| 最近记录: |