c# - 在 C# 3.5 中向下转换泛型类型

标签 c# .net generics downcast

为什么我只能向上转换泛型而不能向下转换?
编译器为什么不清楚如果我的约束说 where T : BaseClass and U is derived from BaseClass that (U)objectOfTypeT is valid?

最佳答案

因为它可能无效。考虑一下:

class Base { }
class A : Base { }
class B : Base { }

A temp1 = new A();
B temp2 = (B)temp1; // not valid

仅仅因为它们共享相同的基类并不意味着您可以将一个类型转换为另一个。

请注意,您可以使用 as 运算符来解决此问题:

var result = objectOfTypeT as U; // this does not give any compilation error
                                 // but will result in a null reference if
                                 // objectOfTypeT cannot be converted to U

关于c# - 在 C# 3.5 中向下转换泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4007497/

相关文章:

c# - 在 Entity Framework 中使用事务或锁定来确保正确操作

c# - MVC 路由在根目录中拾取区域 Controller

c# - 强制 HttpClient 获取新版本的源

c# - 在 UWP 中将 Entity Framework 与 SQL Server 结合使用

c# - 同时远程多次执行SSIS包

.net - 上传时获取原始文件创建日期

c# - 如何使二进制乘法运算符 * 在泛型类中可用?

c# - 递归地使用泛型反射

c# - 如何在 Web 服务中返回通用字典

c# - 在 WPF 中渲染清晰的线条