gpt4 book ai didi

c# - 为什么不能从泛型约束中隐式推断出 `this` 的类型转换?

转载 作者:行者123 更新时间:2023-11-30 13:29:53 25 4
gpt4 key购买 nike

我有以下类(class):

public class Item<TItem>
where TItem : Item<TItem>
{
void GetReference()
{
TItem item = this;
}
}

在这里TItem item = this;生成编译器错误“无法将 Item<TItem> 隐式转换为 TItem”。

但是为什么我们需要在这里进行转换呢?我们已经定义了约束 where TItem : Item<TItem> , 因此可以认为根本不需要转换,因为这两种类型是相同的,不是吗?

顺便说一句,显式转换是可用的。这也在编译器错误中说明。

最佳答案

因为这样不安全。考虑:

public class GoodItem : Item<GoodItem>
{
// No problem
}

public class EvilItem : Item<GoodItem>
{
// GetReference body would be equivalent to
// GoodItem item = this;
// ... but this *isn't* a GoodItem, it's an EvilItem!
}

EvilItem满足 TItem 的约束没有问题 - GoodItem确实源自 Item<GoodItem> .

无法表达正在声明的和类型参数之间的关系,而这正是您真正想要的。

关于c# - 为什么不能从泛型约束中隐式推断出 `this` 的类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46834933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com