简体   繁体   English

我可以在 C# 中使用三元运算符运行多个语句吗?

[英]Can I run a number of statements using a ternary operator in C#?

I have an object named MyObject .我有一个名为MyObject的 object 。 This has a property Name.这有一个属性名称。

Can I use the ternary operator like the following我可以像下面这样使用三元运算符吗

string validSite = 'yahoo';
string invalidSite ='abc';
MyObject obj = new MyObject()

I want to perform a few statements in the true condition我想在真实条件下执行一些语句

valid ? ({ validSite; obj.Name = 'Test';})  : invalidSite

Is there a way to do this or do I need to use if-else?有没有办法做到这一点,还是我需要使用 if-else?

Note below are possible solutions to the situation mentioned above but they are not recommended.以下注意是上述情况的可能解决方案,但不推荐使用。 As comment from @Hans Kesting on question I totally agree with using plain if...else... statement instead of one liner if your scenario is as simple as you mentioned in question.正如@Hans Kesting 对问题的评论,如果您的情况像您在问题中提到的那样简单,我完全同意使用普通的if...else...语句而不是one liner

Still this answer will help to know what could be the possible ways to achieve it and one can use it where this code fits best.这个答案仍然有助于了解实现它的可能方法,并且可以在此代码最适合的地方使用它。


You can do something like below with Func define your statement inside new Func(...) and immediately invoke it with () .您可以使用Func执行以下操作,在new Func(...)中定义您的语句并立即使用()调用它。

var site = valid ? new Func<string>(() => { validSite; obj.Name = 'Test'; return obj.Name; })() : invalidSite;

Alternatively you can use Lazy<T> like below.或者,您可以使用Lazy<T>如下所示。 Use Lazy instead of func and evaluate expression with .Value at the end.使用Lazy而不是func并在末尾使用.Value评估expression

var site = valid ? new Lazy<string>(() => { validSite; obj.Name = 'Test'; return obj.Name; }).Value : invalidSite;

I recommend you to use Local function which can provide re-usability of code if you need same code to repeat multiple times or else you can simply use if...else... if it fits to your requirement.建议您使用Local function如果您需要repeat多次same code或者您可以简单地使用if...else...如果它符合您的要求,它可以提供代码的可re-usability

If you are using C#7 or newer version then you can use local functions .如果您使用的是C#7或更新版本,那么您可以使用本地函数 Inside this local function you can also use all local variables from parent function.在这个局部 function 中,您还可以使用父 function 中的所有局部变量。

public void function Test()
{       
    var site = valid ? GetSite() : invalidSite; 
    
    string GetSite()
    {
        validSite; 
        obj.Name = 'Test'; 
        return obj.Name;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM