【问题标题】:Cleanest way to get a concrete type based on input in c#根据 c# 中的输入获取具体类型的最简洁方法
【发布时间】:2014-07-17 06:03:15
【问题描述】:

我有一个方法如下,它有点像工厂,给定一个字符串类型,我返回一个实现 IWorkerJob 的具体类型。有没有比使用带有 60 种类似情况的 switch 语句更好/更清洁的方法来做到这一点,也许是某种查找?

private static IWorkerJob GetWorkerJob(string type)
    {
        switch (type)
        {
            case WorkerJobType.IMPORT_GOOGLE_JOB:
                return new ImportGoogleJob();
            case WorkerJobType.IMPORT_XYZ_JOB:
                return new ImportXyzJob();

            ....

            default:
                return null;
        }
    }

【问题讨论】:

  • 我认为你现在拥有的一切都很好,真的。只要可读。也许另一种选择是使用反射并根据枚举名称创建类型,但是我不确定这是一种真正“更好/更清洁的方式”:)

标签: c# .net windows windows-services


【解决方案1】:

您可以使用generic methodwhere T : new() 约束以及where T : <interface name>,您可以阅读MSDN 文章Constraints on Type Parameters 上有关约束的更多信息

private static IWorkerJob GetWorkerJob<T>() where T:IWorkerJob, new()
{
    return new T();
}

【讨论】:

    【解决方案2】:

    是的,创建一个映射Func 的字典,然后使用它来创建实例。

    类似这样的:

    private static readonly Dictionary<string, Func<IWorkerJob>> workerJobFactories = new Dictionary<string, Func<IWorkerJob>>
    {
        {WorkerJobType.IMPORT_GOOGLE_JOB, () => new ImportGoogleJob()},
        {WorkerJobType.IMPORT_XYZ_JOB, () => new ImportXyzJob()}
        ...
    };
    
    private static IComparable GetWorkerJob(string type)
    {
        Func<IWorkerJob> factory = null;
        if (workerJobFactories.TryGetValue(type, out factory))
        {
            return factory();
        }
        return null;
    }
    

    另外我建议你为WorkerJobType 创建一个enum 而不是使用字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 2011-04-04
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多