首页 > 解决方案 > 我可以将从数组中获取与创建数组相结合吗?

问题描述

有没有办法可以将此代码重构为一个语句:

// Following line used referenced only once
public static Color[] TabBarBackgroundColor      = { greyEF, grey00, grey00 }; 

// Here's where it's referenced
Current.Resources["TabBarBackgroundColor"]  = Styles.TabBarBackgroundColor[thc];

标签: c#

解决方案


如果不初始化静态变量:

  Current.Resources["TabBarBackgroundColor"]  = (new[]{ greyEF, grey00, grey00 })[thc];

或者您甚至不需要数组来存储帖子中显示的值:

  Current.Resources["TabBarBackgroundColor"]  = thc == 0 ? greyEF : grey00;

如果您确实需要延迟初始化静态变量:

 public static Color[] TabBarBackgroundColor = null;

  Current.Resources["TabBarBackgroundColor"]  = 
       (TabBarBackgroundColor == null ? 
             TabBarBackgroundColor = (new[]{ greyEF, grey00, grey00 }) :
             TabBarBackgroundColor)[thc];

请注意,它看起来更像是重构,我不建议在其他人需要阅读的代码中这样做。


推荐阅读