在 C# (3.0) 中使用条件 (?:) 运算符进行方法选择? [英] Using conditional (?:) operator for method selection in C# (3.0)?

查看:28
本文介绍了在 C# (3.0) 中使用条件 (?:) 运算符进行方法选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一些代码.

现在有很多地方有这样的功能:

Right now there are quite a few places with functions like this:

string error;
if (a) {
   error = f1(a, long, parameter, list);
}
else {
   error = f2(the_same, long, parameter, list);
}

在重构 f1 和 f2(它们很大,但做类似的事情)之前,我想重构为:

before refactoring f1 and f2 (which are large, but do similar things), I'd like to refactor to:

string error = (a ? f1 : f2)(a, long, parameter, list);

就像在 C 中所做的一样.(函数签名是相同的)

As one would do in C. (The function signatures are identical)

但我收到一个错误:

错误 13 无法确定条件表达式的类型,因为'方法组'和'方法组'之间没有隐式转换"

这将使我能够通过初始重构提供不变的行为来识别参数列表是相同的,并且还可以在一个地方重构调用,确保在所有这些不同的重构过程中,当我更改调用接口时没有任何损坏方法.

This would allow me to recognize that the parameter lists are identical by the initial refactoring giving invariant behavior, and also refactor the calls in a single place, ensuring that all during these various refactorings, nothing gets broken as I change the calling interface to the method.

我是否遗漏了一些允许接近此语法的小东西(而不是一大堆额外的委托类型定义等)?

Am I missing something small which would allow a syntax close to this to work (as opposed to a whole bunch of extra delegate type definitions etc)?

抱歉编辑,但实际上有一个返回值,而且很不幸,它是一个字符串.;-(

Sorry to edit, but there is actually a return value, and yes, unfortunately, it is a string. ;-(

现在,我正在接受:

string error = a ? f1(a, long, parameter, list) : f2(a, long, parameter, list);

问题是参数列表确实很长,而且会被重构,我更愿意先合并它们,并在更改它们时处理编译器错误.

The problem is that the parameter list are indeed very long, and are going to get refactored, and I'd prefer to have them consolidated first and deal with compiler errors as I change them.

推荐答案

正如您所指出的,您可以通过声明一个委托来做到这一点.

You can do that by declaring a delegate, as you pointed out.

我注意到您写道,您在很多地方都在这样做.另一种可能更合适的替代方法是使用接口.根据 a 的值实例化两种不同类型之一,然后调用该对象的方法.

I notice that you wrote that you are doing this in quite a few places. Another alternative that might be more suitable is to use interfaces. Instantiate one of two different types depending on the value of a, then call the method on that object.

IFoo foo = a ? new Foo1() : new Foo2();
foo.f(a, long, parameter, list);

如果您有多个方法需要根据 a 的值同时更改,那么您可以将它们全部包含在同一个界面中,您只需要测试 a> 一次.

If you have multiple methods that need to change simultaneously depending on the value of a then you can include them all in the same interface and you will only need to test a once.

这篇关于在 C# (3.0) 中使用条件 (?:) 运算符进行方法选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆