如何在"可能"类型的对象之间切换?

Vim*_*987 3 .net c# types switch-statement

可能重复:
C# - "开启类型"有比这更好的选择吗?

我的公司遗留代码有如下内容

public override Uri GetUri(object obj)
{
    if ((obj is Entry) || (obj is EntryComment))
    {
        //
    }
    if (obj is Blog)
    {
        //
    }

    // if obj is blah blah blah
}
Run Code Online (Sandbox Code Playgroud)

这种方法很难看.我想重构它,但我不知道迭代obj可能的"可能"类型的技术.

我怎么能重构这个?

谢谢.

Jon*_*eet 5

有两种选择:

  • 如果您使用的是C#4,则可以使用动态类型,并将该方法拆分为多个重载:

    public Uri GetUri(dynamic obj)
    {
        return GetUriImpl(obj);
    }
    
    private Uri GetUriImpl(Entry entry)
    {
        ...
    }
    
    private Uri GetUriImpl(EntryComment comment)
    {
        ...
    }
    
    Run Code Online (Sandbox Code Playgroud)

    在这种情况下,如果它不是已知类型,您可能需要某种"逆止"方法.

  • 你可以创建一个Dictionary<Type, Func<object, Uri>>:

    private static Dictionary<Type, Func<object, Uri>> UriProviders = 
        new Dictionary<Type, Func<object, Uri>> {   
        { typeof(Entry), value => ... },
        { typeof(EntryComment), value => ... },
        { typeof(Blog), value => ... },
    };
    
    Run Code Online (Sandbox Code Playgroud)

    然后:

    public Uri GetUri(object obj)
    {
        Func<object, Uri> provider;
        if (!UriProviders.TryGetValue(obj.GetType(), out provider))
        {
            // Handle unknown type case
        }
        return provider(obj);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    请注意,这不包括您收到子类型Entry等的情况.

这些都不是特别好,请注意......我怀疑更高级别的重新设计可能更可取.


归档时间:

查看次数:

1006 次

最近记录:

11 年,2 月 前