Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

.net - Using conditional (?:) operator for method selection in C# (3.0)?

I'm refactoring some 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);
}

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);

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

But I get an error:

"Error 13 Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'"

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);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the ? to work the compiler needs an explicit type for at least one of the operands. You can provide one here via a cast operator

(a ? (Action<T1,T2,T3,T4>)f1 : f2)(a, long, parameter, list);

Replace T* with the actual types of the delegate parameters


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...