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

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

问题描述

我重构一些code。

现在有好几个地方有这样的功能:

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)

不过,我得到一个错误:

But I get an error:

的条件EX pression错误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. ;-(

现在,我满足于这样的:

Right now, I'm settling for this:

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

现在的问题是,该参数列表确实很长,而且会得到重构,而且我preFER让他们第一次综合和处理编译器错误,因为我改变他们。

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 然后,可将它们都在同一界面,你只需要测试<值多种方法code> 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天全站免登陆