如何将值转换为元组(字符串,布尔值)

How cast value as tuple (string, bool)

这样可以转换为元组吗?

(string value, bool flag) value1 = MethodInfo.Invoke(this, param) as (string, bool);

不幸的是它抛出:

"The as operator must be used with a reference type or nullable type ('(string, bool)' is a non-nullable value type)"

只能这样工作:

Tuple<string, bool> value1 = MethodInfo.Invoke(this, param) as Tuple<string, bool>;

您可以使用强制转换表达式来强制转换:

(string value, bool flag) tuple = ((string, bool)) MethodInfo.Invoke(this, param);

但与使用 as 不同,如果 Invoke 的 return 值不是 (string, bool),这将崩溃。如果你不喜欢那样,你可以使用模式匹配:

if (methodInfo.Invoke(this, param) is (string value, bool flag))
{
    Console.WriteLine($"({value}, {flag})");
    // assign it to a new variable if you want it as one "thing":
    (string value, bool flag) tuple = (value, flag);
}