技术开发 频道

封装 if/else、swith/case及while

      调用代码也要修改:

public static void Test2()
        {
            
//扩展方式
            int int0 = -121;
            
int int1 = int0.If(i => i < 0, i => -i)
                .If(i
=> i > 100, i => i - 100)
                .If(i
=> i % 2 == 1, i => i - 1);
            
//常规方式
            int int3 = -121;
            
if (int3 < 0) int3 = -int3;
            
if (int3 > 100) int3 -= 100;
            
if (int3 % 2 == 1) int3--;
        }

  引用类型及值类型的扩展我们已经完成,用string来测试一下吧,如下:

public static void Test3()
        {
            
//从邮箱变换成主页
            string email = "ldp615@163.com";
            
string page = email.If(s => s.Contains("@"), s => s.Substring(0, s.IndexOf("@")))
                .If(s
=>! s.StartsWith("www."), s => s = "www." + s)
                .If(s
=>! s.EndsWith(".com"), s => s += ".com");
        }

  但编译不通过,会提示错误:

  这个错误比较怪,我们写了两个扩展,一个是给值类型的,一个给引用类型,可string类型在这里都不行。

0
相关文章