gpt4 book ai didi

c# Upcast 与泛型

转载 作者:行者123 更新时间:2023-11-30 14:48:51 31 4
gpt4 key购买 nike

我定义了一个带有抽象约束的抽象类:

abstract class Asset<P> where P : Parm { }
abstract class Parm { }

class StockParm : Parm { }
class Stock : Asset<StockParm> { }

class BondParm : Parm { }
class Bond : Asset<BondParm> { }

List<Asset<Parm>> assets = new List<Asset<Parm>>();
Stock stock;
assets.Add(stock);

但是我收到了错误信息:

"Cannot convert type Stock to Asset"

有没有办法列出所有的 Assets

谢谢

最佳答案

你需要向编译器解释 Asset<Derived>Asset<Base> .编译器将泛型类编译为 deperate 类 - 每个类一个 T .告诉编译器“ok”的名称是 covariant .

MSDN:

Covariance - Enables you to use a more derived type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable.

更改 Asset<T>到界面并添加 out keyword :

 interface Asset<out P> where P : Parm { }

public static class Program
{
public static void Main(string[] args)
{
List<Asset<Parm>> assets = new List<Asset<Parm>>();
Stock stock = new Stock();
assets.Add(stock);
}
}

public abstract class Parm { }
public class StockParm : Parm { }

public interface Asset<out P> where P : Parm { }
public class Stock : Asset<StockParm> { }

关于c# Upcast 与泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40128523/

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