【问题标题】:How optimize many conditions with casting?如何通过铸造优化许多条件?
【发布时间】:2019-02-07 15:49:07
【问题描述】:

请问可以用字典优化这段代码吗?否则。

if (node.Type.Equals(NodeType.CONTAINER))
{
    DataUtils.ContainerToData((INode<ContainerValue>) node, data);
}
else if (node.Type.Equals(NodeType.TEXT))
{
    DataUtils.TextToData((INode<TextValue>) node, data);
}

我有 15 个这样的条件。

我认为字典会起作用,但是如何进行强制转换? (INode&lt;pair.Value&gt;) node。我正在寻找这样的解决方案:

var dictionary = new Dictionary<string, Type>();
dictionary.Add(NodeType.CONTAINER, tyeof(ContainerValue));
dictionary.Add(NodeType.TEXT, tyeof(TextValue));

foreach (var pair in dictionary)
{
    if(node.Type.Equals(pair.Key))
    {
        // wrong
        DataUtils.ContainerToData((INode<pair.Value>) node, data);
    }
}

【问题讨论】:

  • "但是如何重新输入?" - 抱歉,没听懂。
  • data 的类型是什么?
  • retype = cast :)
  • 你的第一个 sn-p 包含DataUtils.TextToData,对吗?
  • 数据或节点的详细信息不重要。它是对象

标签: c# optimization


【解决方案1】:

我认为你可以使用 switch 语句:

csharp-pattern-matching-7-0

                switch (node)
                {
                    case INode<ContainerValue> containerValue:
                        DataUtils.ContainerToData(containerValue, data);
                        break;
                    case INode<TextValue> textValue:
                        DataUtils.ContainerToData(textValue, data);
                        break;

                }

希望对您有所帮助。

【讨论】:

  • 谢谢,但我需要先检查node.Type.Equals 并将条件重写为foreach 循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 2017-08-14
相关资源
最近更新 更多