gpt4 book ai didi

c# - 太多 if (obj is thisObj) 语句

转载 作者:可可西里 更新时间:2023-11-01 07:59:58 25 4
gpt4 key购买 nike

我目前有一种方法试图找出它收到的对象是什么。它知道在某个接口(interface)上,例如 IService,但我有代码查看它并试图告诉我它是 Service1 还是 Service2。我目前有很多 if(obj is thisObj) 样式语句,什么是使这段代码漂亮的最佳解决方案?

这是我所拥有的示例:

    public void DoSomething(IService service)
{
if (service is Service1)
{
//DO something
}

if (service is Service2)
{
//DO something else
}
}

现在有两个并不是什么坏事,但我正在考虑可能有 20 多个这样的东西,使用起来会很糟糕。

有什么想法吗?


好的,我认为需要更多详细信息,它们在这里:

在此方法之前,我有另一种方法,它接收一个 xml 文档,它们反序列化到接口(interface) IService 中,所以我们有这样的东西:

    private static void Method(InnerXml)

{

var messageObj = (IServiceTask)XmlSerialization.Deserialize(typeof(IServiceTask), InnerXml);

var service = GetService(messageObj);
service.PerformTask(xmlDoc);

}

private static IService GetService(IServiceTask messageObj)
{
var service = new IService ();

if (messageObj is Task1)
{
service = (SomeService)messageObj;
}

if (messageObj is Task2)
{
service = (SomeOtherService)messageObj;
}
return service ;
}

希望这能让它更清楚一些。

最佳答案

你能改变 IService 吗?

添加方法 DoSomething() 并在所有服务中实现它。

关于c# - 太多 if (obj is thisObj) 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024347/

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