gpt4 book ai didi

c# - 将具体转换为基础通用抽象类的解决方法

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

我有一个通用的基础抽象类:

public abstract class Generator<T>
{
public abstract void Start(T config);
}

然后,我有许多从基类继承并期望特定参数类型的具体类。其中一些:

public class AGenerator : Generator<AGeneratorConfig>
{
public override void Start(AGeneratorConfig Config) { /* some code*/ }
}

public class BGenerator : Generator<BGeneratorConfig>
{
public override void Start(BGeneratorConfig Config) { /* some code*/ }
}

它们的Start()方法参数定义如下:

public abstract class GeneratorConfig
{
public int CommonProperty {get; set;}
}

public class AGeneratorConfig : GeneratorConfig
{
// Some props specific for AGenerator
}

public class BGeneratorConfig : GeneratorConfig
{
// Some props specific for BGenerator
}

最后,我有一个类似客户端/管理器/工厂的类,它使用提供的配置处理实际的发电机启动过程,但是使用类型转换具体来抽象泛型类:

public class GeneratorClient
{
public static void StartGenerator<T>(T config)
{
Generator<T> generator = null;

if (config is AGeneratorConfig)
{
generator = new AGenerator() as Generator<T>; // casting to abstract base class
}
else if (config is BGeneratorConfig)
{
generator = new BGenerator() as Generator<T>; // casting to abstract base class
}
else
{
throw new NotImplementedException();
}

generator.Start(config);
}
}

我的问题:是否有任何解决方法可以消除将具体转换为抽象基类的需要?

最简单的解决方案是这样的:

public static void StartGenerator<T>(T config)
{
if (config is AGeneratorConfig)
{
var generator = new AGenerator();
generator.Start(config);
}
else if (config is BGeneratorConfig)
{
var generator = new BGenerator();
generator.Start(config);
}
else
{
throw new NotImplementedException();
}
}

但对于每个新创建的具体生成器对象,generator.Start(config); 需要重复。

最佳答案

定义 generator正如object并将其转换为 Generator<T>仅在最后一次调用时:

public static void StartGenerator<T>(T config)
{
object generator = null;

if (config is AGeneratorConfig)
{
generator = new AGenerator();
}
else if (config is BGeneratorConfig)
{
generator = new BGenerator();
}
else
{
throw new NotImplementedException();
}

((Generator<T>)generator).Start(config);
}

关于c# - 将具体转换为基础通用抽象类的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543526/

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