C# 中左侧操作数的三元条件运算符

Ternary conditional operator for the left-hand operand in C#

是否可以在没有 if 语句的情况下根据某些内联条件选择目标变量?

(!RTL ? padLeft : padRight) = NearBorder.LineWidth;

让我们试一试,看看会发生什么:

var a =1; var b =1; var c=1;
(a == 1? b : c) = 4

如果你运行这个你会得到

The left-hand side of an assignment must be a variable, property or indexer Which is referring to everything left of that = sign.

然而,您可以有条件地分配给一个变量或另一个变量,但您必须两次使用您的分配变量。这会像您期望的那样工作:

!RTL ? padLeft = NearBorder.LineWidth : padRight = NearBorder.LineWidth;

但是在您的具体情况下,我可能会使用不同的代码。

padLeft = RTL ? NearBorder.LineWidth: 0;
padRight = !RTL ? NearBorder.LineWidth: 0;

好吧,如果您使用三元运算符 select 委托并让委托进行赋值,则有可能。您是否会在实际使用中看到这种技术值得怀疑。通常使用 if 语句。

    var a = new Action<int>( i => padLeft = i );
    var b = new Action<int>( i => padRight = i );

    (!RTL ? a : b)(NearBorder.LineWidth);

如果您使用的是足够新的 C# 版本 (7.2+),并且这些变量是局部变量或字段,那么您可以使用 ref locals;

(!RTL ? ref padLeft : ref padRight) = NearBorder.LineWidth;

查看此 sharplab link for an example. Note that the proposal docs (which refer to this as conditional ref) indicate that this is still a proposal. The Championed GitHub issue is still open but seems to indicate the only thing missing is a true specification. This comment on that issue suggests it was all implemented as part of the greater ref readonly 主题。

总而言之,这段代码在 SharpLab 和本地 VS2019(最新,非预览版,使用 dotnet core 3.0)中对我都有效

如果这些变量是字段,您 可以 也可以使用 ref return 并将逻辑封装到一个函数中。例如:

// class fields
int padLeft, padRight;  
// ref returning method 
private ref int GetPad() => ref (!RTL ? ref padLeft : ref padRight);
// actually use it
void SetPad() {
    // assignment to a method! 
    GetPad() = NearBorder.LineWidth;
} 

有关 ref localsref returns(最初是 C# 7 的一部分)概念的更多信息,请参阅这篇 MSDN 文章。