How to call a method overload based on closed generic type?

后端 未结 6 2018
时光取名叫无心
时光取名叫无心 2021-02-13 10:20

Suppose I have three methods:

void Foo(MemoryStream v) {Console.WriteLine (\"MemoryStream\");}
void Foo(Stream v)       {Console.WriteLine (\"Stream\");}
void Fo         


        
6条回答
  •  余生分开走
    2021-02-13 10:51

    This is not a "pretty" answer (indeed, since this is kinda subverting the intent of generics, it is hard to find a pretty answer inside the language), but you could perhaps code the overload lookups via a dictionary:

    static readonly Dictionary> overloads
        = new Dictionary> {
            {typeof(Stream), o => Foo((Stream)o)},
            {typeof(MemoryStream), o => Foo((MemoryStream)o)}
        };
    public static void Bar() {
        Action overload;
        if (overloads.TryGetValue(typeof(T), out overload)) {
            overload(default(T));
        } else {
            Foo((object)default(T));
        }
    }
    
    
    

    This isn't nice, and I don't recommend it. For easier maintenance, you could perhaps move the overloads population to a static constructor / type initalizer, and populate it via reflection. Note also that this only works for exact T - it won't work if someone uses an unexpected type (Bar for example) - although you could presumably loop over the base-types (but even then, it doesn't have great support for interfaces etc).

    This approach doesn't have much to recommend it, all things considered. I would probably advise approaching the entire problem from a different angle (i.e. removing the need to do this).

    提交回复
    热议问题