gpt4 book ai didi

c# - 如何在C#中将entitybase类型转换为实体类型

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:39 26 4
gpt4 key购买 nike

我在 .NET 3.5 中尝试了以下代码,但在注释中显示的行出现异常:

无法将类型“TUnpaid”转换为“ClassLibrary1.Unpaid”

如何在 .NET 3.5 中解决这个问题?

namespace ClassLibrary1
{
public class EntityBase
{
public virtual void Save<T>(T dok) where T : EntityBase, new()
{
}
}

public class Unpaid : EntityBase
{
public override void Save<TUnpaid>(TUnpaid dok)
{
// Cannot convert type 'TUnpaid' to 'ClassLibrary1.Unpaid'
var kup = (Unpaid)dok;
}
}
}

最佳答案

如果您将 EntityBase 类设为泛型,我认为您可以解决这个问题:

public class EntityBase<T>
{
public virtual void Save<T>(T dok) where T : EntityBase<T>, new()
{
}
}

public class Unpaid : EntityBase<Unpaid>
{
public override void Save<Unpaid>(Unpaid dok)
{
// dok is now of type Unpaid and doesn't need the cast
}
}

关于c# - 如何在C#中将entitybase类型转换为实体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7385050/

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