c# - 我可以将从数组中获取与创建数组相结合吗?
问题描述
有没有办法可以将此代码重构为一个语句:
// 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];
解决方案
如果不初始化静态变量:
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];
请注意,它看起来更像是重构,我不建议在其他人需要阅读的代码中这样做。
推荐阅读
- javascript - 最小化条件语句的代码
- awk - 如果在文件的行中找到某个值,则使用 AWK 打印相邻字段
- python - PyQt4 QSqlDatabase:未加载 QMYSQL 驱动程序
- c++ - 在 dlmopen 之后使用 dlsym 时出现分段错误,但使用 dlopen dlsym 工作正常
- react-native - 为什么我使用 `useRef` 创建的我的参考会产生此错误消息?
- google-apps-script - LanguageApp.translate 限制
- demo - “The Mother of All Demos”是用什么语言写的?
- android - Android Studio 警告“此 IDE 正在低内存中运行,而且 android studio 一直没有响应
- json - 为什么 Spring API 在同一个请求中返回 2 个响应?
- python - Python_打印函数的结果