【发布时间】:2019-06-15 15:24:18
【问题描述】:
我想将我的许多 if 更改为查找表。
我有类型和方法。我想把它们配对。
if (propertyType == typeof(bool) || propertyType == typeof(bool?))
DoBool(propertyType);
if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
DoDateTime(propertyType);
if (propertyType == typeof(Guid) || propertyType == typeof(Guid?))
DoGuid(propertyType);
我必须创建一个Dictionary<Type, Action>()?或者这是最好的优雅方式?
您能否给我一些建议,我可以从哪里开始或在哪里可以找到解决方案?
【问题讨论】:
-
您当然可以创建一个
Dictionary<Type, Action<Type>>- 这听起来就像您向我们展示的内容一样。 -
@JonSkeet 谢谢,当我创建这个字典时,我如何使用它来代替 if 语句?
-
if (myDictionary.TryGetValue(myType, out var action)) action(myType);:检查给定类型(myType)是否存在action,如果存在,则执行action -
如果您确信总会有一个条目,您可以使用
dictionary[propertyType].Invoke(propertyType)。否则,您需要使用TryGetValue并仅在有条目时才调用该值。鉴于propertyType无论如何都是关键,您当然可以使用Dictionary<Type, Action>并只注册将在必要时传递适当参数的操作。如果不了解您的方法,很难知道什么是最好的。 -
@JonSkeet 感谢您的回答,对我帮助很大。
标签: c# dictionary methods types lookup-tables