使用三元运算符调用方法

发布于 2024-10-27 19:52:54 字数 791 浏览 8 评论 0原文

在尝试新概念时,我发现了三元运算符及其美妙之处。玩了一段时间后,我决定测试一下它的极限。

然而,当我无法编译某行代码时,我的乐趣很快就结束了。

int a = 5;
int b = 10;
a == b ? doThis() : doThat() 

    private void doThis()
    {
        MessageBox.Show("Did this");
    }
    private void doThat()
    {
        MessageBox.Show("Did that");
    }

这一行给了我两个错误:

Error   1   Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Error   2   Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'void'

我从未使用过三元运算符来决定调用哪个方法,我也不知道它是否可能。我只是喜欢用一行 If Else Statement 来调用方法的想法。

我做了一些研究,但找不到任何人这样做的例子,所以我想我可能希望看到一些不可能的事情。

如果可以的话请指点一下我的错误做法,如果不行的话还有其他方法吗?

While playing around with new concepts, I came across the Ternary Operator and its beauty. After playing with it for a while, I decided to test its limits.

However, my fun was ended quickly when I couldn't get a certain line of code to compile.

int a = 5;
int b = 10;
a == b ? doThis() : doThat() 

    private void doThis()
    {
        MessageBox.Show("Did this");
    }
    private void doThat()
    {
        MessageBox.Show("Did that");
    }

This line gives me two errors:

Error   1   Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Error   2   Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'void'

I have never used a Ternary Operator to decide which method to be called, nor do I know if it is even possible. I just like the idea of a one-line If Else Statement for method calling.

I have done a bit of research and I cannot find any examples of anyone doing this, so I think I might be hoping for something impossible.

If this is possible, please enlighten me in my wrong doings, and it isn't possible, is there another way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

千と千尋 2024-11-03 19:52:54

三元运算符用于返回值,并且必须分配这些值。假设方法 doThis()doThat() 返回值,一个简单的赋值即可解决您的问题。

如果你想做你正在尝试的事情,这是可能的,但解决方案并不完美。

int a = 5;
int b = 10;
(a == b ? (Action)doThis : doThat)();

这将返回一个 Action 委托,然后由括号调用该委托。这不是实现这一目标的典型方法。

The ternary operator is used to return values and those values must be assigned. Assuming that the methods doThis() and doThat() return values, a simple assignment will fix your problem.

If you want to do what you are trying, it is possible, but the solution isn't pretty.

int a = 5;
int b = 10;
(a == b ? (Action)doThis : doThat)();

This returns an Action delegate which is then invoked by the parenthesis. This is not a typical way to achieve this.

感情旳空白 2024-11-03 19:52:54

三元运算符必须返回一些东西。典型的用法是这样的:

int x = (a > b) ? a : b;

如果你尝试类似的东西,

a + b;

编译器会抱怨。

(a > b) ? a - b : b - a;

基本上是“a - b”或“b - a”的快捷方式,它们本身并不是合法的语句。

Ternary operator must return something. A typical usage is like this:

int x = (a > b) ? a : b;

If you try something like

a + b;

The compiler will complain.

(a > b) ? a - b : b - a;

is basically a shortcut for either "a - b" or "b - a", which are not legitimate statements on their own.

黑白记忆 2024-11-03 19:52:54

如果您确实想在条件运算符中调用 void 方法,则可以使用委托:

(something ? new Action(DoThis) : DoThat)();

如果方法采用参数,这将变得更加复杂。
您可以将 lambda 表达式放入条件中,也可以使用 Action

然而,这是一件非常愚蠢的事情。

If you really want to invoke void methods in a conditional operator, you can use delegates:

(something ? new Action(DoThis) : DoThat)();

If the methods take parameters, this will become more complicated.
You can either put lambda expressions in the conditional or use Action<T>.

However, this is a very dumb thing to do.

送你一个梦 2024-11-03 19:52:54

不过,您应该能够做到这一点:

        int a = 5;
        int b = 10;

        var func = a == b ? (Action)doThis : (Action)doThat; // decide which method

        func(); // call it

但并不是说它真的那么有用。

You should be able to do this, though:

        int a = 5;
        int b = 10;

        var func = a == b ? (Action)doThis : (Action)doThat; // decide which method

        func(); // call it

Not that it's really that useful though.

毁梦 2024-11-03 19:52:54

上述声明不起作用的原因是由其他用户提供的,实际上并没有回答我的真实问题。

经过更多尝试后,我发现您可以使用此运算符来执行上述语句,但它会导致一些错误的代码。

如果我将上面的语句更改为;

int a = 5;
int b = 10;
int result = a == b ? doThis() : doThat(); 

private int doThis()
{
    MessageBox.Show("Did this");
    return 0;
}
private int doThat()
{
    MessageBox.Show("Did that");
    return 1;
}

该代码将按其应有的方式编译和执行。但是,如果这些方法最初并不打算返回任何内容,并且引用了代码中的其他区域,那么您现在每次调用这些方法时都必须处理一个返回对象。

否则,您现在可以将三元运算符用于单行方法选择器,甚至可以使用结果知道它在下一行中调用哪个方法。

int result = a == b ? doThis() : doThat();

if (result == 0)
   MessageBox.Show("You called doThis()!");

现在,这段代码绝对没有意义,可以通过 If Else 轻松完成,但我只是想知道它是否可以完成,以及你必须做什么才能让它工作。

现在我知道您可以在这些方法中有效地返回任何类型,这可能会变得更有用。它可能被认为是“糟糕的编码实践”,但在它从未想过的情况下可能会变得非常有用。

您可以根据任何条件访问一个或另一个对象,这在一行代码中可能非常有用。

UserPrivileges result = user.Group == Group.Admin ? GiveAdminPrivileges() : GiveUserPrivileges();

private UserPrivileges GiveAdminPrivileges()
{
      //Enter code here
      return var;
}
private UserPrivileges GiveUserPrivileges()
{
      //Enter code here
      return var;
}

当然,这可以通过 If 语句来完成,但我认为将三元运算符用于其他用途会使编程变得有趣。现在,这可能不如 If Else 语句那么有效,在这种情况下,我永远不会使用它。

The reason why the above statement does not work was provided by the other users and effectively did not answer my true question.

After playing around some more, I figured out that you CAN use this operator to do the above statement, but it results in some bad code.

If I were to change the above statement to;

int a = 5;
int b = 10;
int result = a == b ? doThis() : doThat(); 

private int doThis()
{
    MessageBox.Show("Did this");
    return 0;
}
private int doThat()
{
    MessageBox.Show("Did that");
    return 1;
}

This code will compile and execute the way it should. However, if these methods were not originally intended to return anything, and referenced other areas in the code, you now have to handle a return object each time to call these methods.

Otherwise, you now can use a ternary operator for a one-line method chooser and even know which method it called in the next line using the result.

int result = a == b ? doThis() : doThat();

if (result == 0)
   MessageBox.Show("You called doThis()!");

Now, this code is absolutely pointless and could be easily done by a If Else, but I just wanted to know if it could be done, and what you had to do to get it to work.

Now that I know that you can effectively return any type in these methods, this might become a little more useful. It may be considered a "Bad Coding Practice" but might become very useful in situations it was never MEANT for.

You could get access to one object or another based on any condition and that might be very useful in one line of code.

UserPrivileges result = user.Group == Group.Admin ? GiveAdminPrivileges() : GiveUserPrivileges();

private UserPrivileges GiveAdminPrivileges()
{
      //Enter code here
      return var;
}
private UserPrivileges GiveUserPrivileges()
{
      //Enter code here
      return var;
}

Sure, this can be done by an If Statement, but I think that using the Ternary Operator for other uses makes programming fun. Now, this may not be as efficient as an If Else statement, in which case, I would never use this.

-黛色若梦 2024-11-03 19:52:54

条件运算符是一个返回值的表达式。
您不能将其与返回 void 的函数一起使用。

相反,您应该使用普通的 if

The conditional operator is an expression that returns a value.
You cannot use it with functions that return void.

Instead, you should use a normal if.

惟欲睡 2024-11-03 19:52:54

方法 1:使用操作

Action Action = true is true ? new Action(() => A()) : new Action(() => B());
Action.Invoke();

方法 2:使用扩展

Button Button = new Button(){
    IsEnabled = false
};
Button.Switch((x) => x.IsEnabled).Invoke(() => A(), () => B())

扩展开关:

public static R Switch<T, R>(this T sender, Func<T, R> method){
    return method.Invoke(sender);
}

扩展调用:

public static void Invoke(this bool condition, Action @true, Action @false){
    Action Action = condition ? @true : @false;
    Action.Invoke();
}

方法 3:使用扩展和 C# 6.0 null 条件运算符

Button.Case((x) => 0 > 1)?.With(() => A());
Button.Case((x) => 0 < 1)?.With(() => B());

扩展 With :

public static T With<T>(this T sender, Action method){
    method.Invoke();
    return sender;
}

扩展案例:

public static object Case<T>(this T sender, Func<T, bool> method){
    return method.Invoke(sender) ? Convert.ChangeType(sender, typeof(T)) : null;
}

Method 1: Using Action

Action Action = true is true ? new Action(() => A()) : new Action(() => B());
Action.Invoke();

Method 2: Using Extensions

Button Button = new Button(){
    IsEnabled = false
};
Button.Switch((x) => x.IsEnabled).Invoke(() => A(), () => B())

Extension Switch:

public static R Switch<T, R>(this T sender, Func<T, R> method){
    return method.Invoke(sender);
}

Extension Invoke:

public static void Invoke(this bool condition, Action @true, Action @false){
    Action Action = condition ? @true : @false;
    Action.Invoke();
}

Method 3: Using Extensions and C# 6.0 null conditional operator

Button.Case((x) => 0 > 1)?.With(() => A());
Button.Case((x) => 0 < 1)?.With(() => B());

Extension With:

public static T With<T>(this T sender, Action method){
    method.Invoke();
    return sender;
}

Extension Case:

public static object Case<T>(this T sender, Func<T, bool> method){
    return method.Invoke(sender) ? Convert.ChangeType(sender, typeof(T)) : null;
}
猥︴琐丶欲为 2024-11-03 19:52:54

.NET 不(轻易)支持(可读版本)这是有原因的。它非常混乱并且使你的代码难以阅读。逻辑树应该相对容易遍历。如果我走进一份工作,他们的所有代码都使用三元来赋值、调用方法等。我想我会直接走开。

.NET doesn't (easily) support (a readable version of) this for a reason. It's very jankity and makes your code hard to read. Logic trees should be relatively easy to traverse. If I were to walk in to a job and all the code they had used ternary for assigning values, calling methods, etc. I think I would just walk out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文