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

后端 未结 7 1974
日久生厌
日久生厌 2020-12-01 11:49

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,         


        
7条回答
  •  -上瘾入骨i
    2020-12-01 12:44

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

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

    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.

提交回复
热议问题