gpt4 book ai didi

c# - 抽象类中的同步或异步方法

转载 作者:行者123 更新时间:2023-11-30 19:54:37 25 4
gpt4 key购买 nike

我考虑使用以下抽象类作为数据库迁移的基础:

using System.Threading.Tasks;

public abstract class MigrationBase
{
public abstract string Name { get; }
public abstract string Description { get; }
public abstract int FromVersion { get; }
public abstract int ToVersion { get; }
public abstract void Apply();
public abstract Task ApplyAsync();
}

现在,根据将为其编写具体迁移的底层数据库系统,实现 void ApplyTask ApplyAsync 方法可能更有意义。我看到以下选项:

  1. 如果我决定只使用两种抽象方法中的一种,我会强制实现具体迁移的开发人员在 one 中做错或 the other方式“在 50% 的情况下”。
  2. 如果我决定同时使用这两种抽象方法,只要数据库系统不提供这两种可能性,我就会强制他做错。
  3. 拥有 MigrationBaseSyncMigrationBaseAsyncMigrationBase 并在所有地方使用类型转换对我来说似乎不合理。
  4. 我目前是否缺少更好的选择?

现在您可能会说我只能选择选项二,因为 ADO.Net 提供同步和异步方法,在大多数情况下数据库适配器将提供这两种变体。如果不考虑 ADO.Net 而看更一般的问题,是否有更好的解决方案?
如果我选择选项二,我是否应该提供 Task ApplyAsync 的预实现版本,类似于 Microsoft 对 System.IO.Stream.ReadAsync 所做的,同时考虑 Stephen Toub 所写的内容?如果是,我还需要注意什么?

最佳答案

单独使用ApplyAsync,并删除其他方法。

If I decide just having one of both abstract methods, I force the developer implementing the concrete migration to do it wrong either in the one or the other way

如果用户需要从接口(interface)或抽象类中实现一个async 方法,但他必须同步地做所有事情,用async 方法替代绝对没有问题使用同步方法返回一个 Task,该方法返回一个从结果构造的已完成任务。

另一方面,您的代码总是像异步调用一样执行调用。

If I decide having both abstract methods, I force him doing it wrong whenever the database system doesn't offer both possibilities.

没错,公开这两种方法是一个更糟糕的选择。

Having a MigrationBase, SyncMigrationBase and AsyncMigrationBase and using typecasts everywhere doesn't seem reasonable to me.

我认为你是对的,为可以“折叠”到基类中的内容添加一个子类看起来确实比必要的工作更多。

关于c# - 抽象类中的同步或异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41242056/

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