如何在“可能”和“可能”之间切换?对象的类型?
可能的重复:
C# - 有更好的吗除了“打开类型”之外还有其他选择吗?
我公司的遗留代码如下所示。
public override Uri GetUri(object obj)
{
if ((obj is Entry) || (obj is EntryComment))
{
//
}
if (obj is Blog)
{
//
}
// if obj is blah blah blah
}
这种方法很丑陋。我想重构它,但我不知道迭代 obj 的“可能”类型的技术。
我该如何重构这个?
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有几个选项:
如果您使用 C# 4,则可以使用动态类型,并将方法拆分为多个重载:
在这种情况下,您可能需要某种“backstop”方法,以防它不是已知类型。
您可以创建一个
Dictionary>
:然后:
请注意,这不会涵盖您收到
Entry
等子类型的情况。请注意,这不会涵盖您收到
Entry
子类型等 这些特别好,介意你...我怀疑更高级别的重新设计可能更好。A couple of options:
If you're using C# 4, you could use dynamic typing, and split the method into a number of overloads:
In this case you'd probably want some sort of "backstop" method in case it's not a known type.
You could create a
Dictionary<Type, Func<object, Uri>>
:and then:
Note that this won't cover the case where you receive a subtype of
Entry
etc.Neither of these are particularly nice, mind you... I suspect a higher level redesign may be preferable.
您还可以使用接口重构它
,并在所有层次结构中实现该接口。比你可以使用
You can also refactor this with interfaces
and implement this interface in all you hierarchy. Than you can use
我认为 Lasse V. Karlsen 在他的评论中有权利,重新设计也许更合适
你可以创建一个像 Stecya 建议的接口
,然后对于你关心的每个对象,例如
Entry
,你可以,现在你可以在对象上调用它
I think Lasse V. Karlsen has the right of it in his comments, a redesign is more appropriate perhaps
You could create an interface like Stecya suggests
and then for each object that you care for, eg
Entry
, you couldand now you can just call it on the object
您可以拥有一个
List()
,其中包含您想要检查并迭代该列表的所有类型。但我不认为这会使代码更快。You can have a
List<Type>()
with all types you want to check for and iterate that list. but I don't think that makes the code faster.您无法
switch-case
类型。You can't
switch-case
types.