gpt4 book ai didi

c# - 如何编写一个好的离线-在线调度程序

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

假设我有这样的场景:我有 2 个信息存储库,我想访问这两个存储库,但是最好将决定使用哪个存储库的任务留给 common class

目标是使用与我在下面编写的代码类似的东西来完成此操作,但这听起来很糟糕:

where TOnline : class
where TOffline : class
where TContract : class

当然我可以忽略这一点,但基本上我要问的是如何停止使用反射并进行输入。也许有任何设计模式推荐?

代码(如果您将其复制/粘贴到替换 Program 类的控制台应用程序中,您应该能够运行该示例)

using CustomerDispatcher = DispatcherProxy<CustomerOnline, CustomerOffline, ICustomer>;

public interface ICustomer
{
string Get(int id);
}

public class CustomerOnline : ICustomer
{
public string Get(int id)
{
// Get From intranet DB
return "From DB";
}
}

public class CustomerOffline : ICustomer
{
public string Get(int id)
{
// Get From local storage
return "From local storage";
}
}

public class DispatcherProxy<TOnline, TOffline, TContract>
where TOnline : class
where TOffline : class
where TContract : class
{
public TContract Instance { get; set; }

public bool IsConnected { get; set; }

public DispatcherProxy()
{
// Asume that I check if it's connected or not
if (this.IsConnected)
this.Instance = (TContract)Activator.CreateInstance(typeof(TOnline));
else
this.Instance = (TContract)Activator.CreateInstance(typeof(TOffline));
}
}

class Program
{
static void Main(string[] args)
{
var customerDispatcher = new CustomerDispatcher();

Console.WriteLine("Result: " + customerDispatcher.Instance.Get(1));

Console.Read();
}
}

提前致谢!

最佳答案

您可以添加 new() 约束:

public class DispatcherProxy<TOnline, TOffline, TContract>
where TOnline : class, new()
where TOffline : class, new()
where TContract : class //isn't TContract an interface?
{
public TContract Instance { get; set; }

public bool IsConnected { get; set; }

public DispatcherProxy()
{
// Asume that I check if it's connected or not
if (this.IsConnected)
this.Instance = new TOnline() as TContract;
else
this.Instance = new TOffline() as TContract;
}
}

关于c# - 如何编写一个好的离线-在线调度程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12395778/

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