gpt4 book ai didi

c# - 没有隐式引用转换

转载 作者:行者123 更新时间:2023-12-01 22:48:35 25 4
gpt4 key购买 nike

我有以下无法编译的代码。我不知道为什么。有人可以帮忙吗?

var mercedes = new Mercedes().WithEngine(new LargeEngine());
var volkswagen = new Volkswagen().WithEngine(new SmallEngine());

public class Mercedes : Car<LargeEngine>
{
}

public class Volkswagen: Car<SmallEngine>
{
}

public class Engine
{
}

public class LargeEngine : Engine
{
}

public class SmallEngine : Engine
{
}

public class Car<T> where T : Engine
{
internal T? Engine { get; set; }
}

public static class ExtensionMethods
{
public static TCar WithEngine<TCar>(this TCar car, Engine engine)
where TCar : Car<Engine>
{
car.Engine = engine;

return car;
}
}

上面的代码没有编译错误:

The type 'Mercedes' cannot be used as type parameter 'TCar' in thegeneric type or method 'ExtensionMethods.WithConfiguration(TCar,Engine)'. There is no implicit reference conversion from 'Mercedes' to'Car<Engine>'

我的理解是“Mercedes”类型不能隐式转换为“Car ”类型。但我也想不出一种显式转换它的方法。

谢谢!

最佳答案

修改 WithEngine 扩展方法的定义,以采用受限于 Car 类的泛型类型参数,其中 T 是派生自 Engine 类的类型参数。

public static class ExtensionMethods
{
public static TCar WithEngine<TCar, TEngine>(this TCar car, TEngine engine)
where TCar : Car<TEngine>
where TEngine : Engine
{
car.Engine = engine;

return car;
}
}

为什么?

Car<LargeEngine>不继承自 Car<Engine> , 并且不能隐式转换为它。

想象一下,如果泛型类型确实实现了这样的继承。那么我们就可以写出如下代码:

Mercedes mercedes = new Mercedes();
Car<Engine> car = mercedes;

// Clearly *this* should not be allowed
car.Engine = new SmallEngine();

关于c# - 没有隐式引用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74893114/

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