Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 基于c中的输入获取具体类型的最干净方法#_C#_.net_Windows_Windows Services - Fatal编程技术网

C# 基于c中的输入获取具体类型的最干净方法#

C# 基于c中的输入获取具体类型的最干净方法#,c#,.net,windows,windows-services,C#,.net,Windows,Windows Services,我有一个如下的方法,它有点像工厂,给定一个字符串类型,我将返回一个具体的类型,该类型正在实现IWorkerJob。有没有比用一个switch语句处理60个这样的情况(可能是某种查找)更好/更干净的方法呢 private static IWorkerJob GetWorkerJob(string type) { switch (type) { case WorkerJobType.IMPORT_GOOGLE_JOB:

我有一个如下的方法,它有点像工厂,给定一个字符串类型,我将返回一个具体的类型,该类型正在实现IWorkerJob。有没有比用一个switch语句处理60个这样的情况(可能是某种查找)更好/更干净的方法呢

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;
        }
    }
您可以使用
where T:new()
约束以及
where T:
,您可以阅读有关MSDN文章中约束的更多信息

私有静态IWorkerJob GetWorkerJob(),其中T:IWorkerJob,new()
{
返回新的T();
}

是的,创建一个映射
函数的字典,然后使用它创建实例

大概是这样的:

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;
}
private static readonly Dictionary workerJobFactories=new Dictionary
{
{WorkerJobType.IMPORT_GOOGLE_JOB,()=>newimportgooglejob()},
{WorkerJobType.IMPORT_XYZ_JOB,()=>new ImportXyzJob()}
...
};
私有静态IComparable GetWorkerJob(字符串类型)
{
Func factory=null;
if(WorkerJobFactorys.TryGetValue(类型,出厂))
{
返回工厂();
}
返回null;
}

另外,我建议您为
WorkerJobType
创建
enum
,而不是使用字符串。

我认为您现在拥有的是很好的,真的。只要可读。也许另一种选择是使用反射并基于枚举名称创建类型,但是我不确定这是否真的是一种“更好/更干净的方法”:
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;
}