title author date CreateTime categories
dotnet 数组自动转基类数组提示 Co-variant array conversion 是什么问题
lindexi
2019-08-31 16:55:58 +0800
2019-03-26 14:27:11 +0800
dotnet

在 C# 的语法,可以提供自动将某个类的数组自动转这个类的基类数组的方法,但是这样的转换在 Resharper 会提示 Co-variant array conversion 这是什么问题?

在 C# 使用强类型,也就是默认在某个类型的数组里面,不能存放不继承当前数组类型的类。在自动转换基类的数组的时候,实际的对象还是原来的类。

如我可以使用下面的代码将 string 数组转换为 object 数组

            string[] foo = new[]
{
"lindexi",
"欢迎访问我博客 https://blog.lindexi.com/ 里面有大量 UWP WPF 博客"
}; object[] f1 = foo;

但是这不代表 f1 也是 object 数组,只是用起来可以作为 object 数组用,如果我存放一个不是继承字符串的类,那么将会提示 System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. 因为这个数组是强数组,不能加入和数组定义不相同的

            string[] foo = new[]
{
"lindexi",
"欢迎访问我博客 https://blog.lindexi.com/ 里面有大量 UWP WPF 博客"
}; object[] f1 = foo; f1[1] = 10;// System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.

object[] f1 = foo 有 Resharper 提示 Co-variant array conversion can cause run-time exception 告诉你不建议这样写

但是如果我定义的时候,将 foo 修改为 object 数组就没有这个问题

            object[] foo = new object[]
{
"lindexi",
"欢迎访问我博客 https://blog.lindexi.com/ 里面有大量 UWP WPF 博客"
}; object[] f1 = foo; f1[1] = 10;

这个方法就是将这个数组定义的类尽可能底层这样就可以让数组加入继承定义的数组的类的

但是更多的是在 Linq 的时候使用,如我从一个 Foo 方法里面拿到了字符串数组,此时我需要将这个数组转换为 object 数组,那么也会有相同提示

            object[] foo = new List<string>
{
"lindexi",
"欢迎访问我博客 https://blog.lindexi.com/ 里面有大量 UWP WPF 博客"
}.ToArray();
// Resharper 提示 Co-variant array conversion can cause run-time exception 因为 ToArray 返回的是 string[] 也就是通过 foo 拿到的是强数组

需要解决这个问题可以使用 ToArray 的方法,让返回的是 object 数组

            object[] foo = new List<string>
{
"lindexi",
"欢迎访问我博客 https://blog.lindexi.com/ 里面有大量 UWP WPF 博客"
}.ToArray<object>();

Co-variant array conversion

Eric Lippert post

最新文章

  1. 尝试在你浏览器的Console(F12)中运行一下,你会发现页面被不同的颜色块高亮了(css调试中学到的js)
  2. Pascal 语言中的关键字及保留字
  3. Windows 10 技术预览版9926 “未知源”引起系统休眠后自启的解决办法
  4. 5、android ConnectivityManager获取网络状态
  5. Temporary-Post-Used-For-Style-Detection-Title-1901742601
  6. 最全的dedeCMS标签调用技巧和大全
  7. weak nonatomic strong等介绍(ios)
  8. Java_log4j
  9. 《Nodejs开发加密货币》之二十七:开发通用的HTML组件
  10. magent——memcached缓存代理服务器
  11. javascript正則表達式 &amp;quot;\b&amp;quot;问题
  12. elasticsearch的rest搜索--- 安装
  13. linux命令readlink
  14. php-fpm 与 fastCgi的浅谈
  15. Spring IOC容器分析(4) -- bean创建获取完整流程
  16. Eclipse install new software无反应
  17. BZOJ2839集合计数
  18. ltp执行过程总结
  19. opencv 3.2安装
  20. 用一次FastDFS

热门文章

  1. 2019 年百度之星&#183;程序设计大赛 - 初赛四 1001 Strassen
  2. shell 检查文件夹是否包含文件,或者只是空文件
  3. 并发编程(二)——利用Process类开启进程、僵尸进程、孤儿进程、守护进程、互斥锁、队列与管道
  4. springboot1.5.x升级到2.1.x切换分支导致的maven依赖混乱
  5. [已解决]报错SyntaxError: Non-ASCII character &#39;\xe6&#39;
  6. git提交遇到.suo文件无法提交的问题
  7. mongo之find结果对象map实例处理
  8. 使用fastClick.js所产生的一些问题
  9. js实现各种复制功能
  10. Tomcat7安装和配置以及优化