动态转换为IEnumerable <T>或T.

bfl*_*mi3 2 c# generics reflection

我有一个接受的类,T并且有一个方法可以获取HttpResponseMessage并修改响应中的内容.

public class MyClass<T> {

    HttpResponseMessage Modify(HttpResponseMessage response) {
        T content;
        if(response.TryGetContentValue(out content)) {
            DoSomethingWithContent(content);
        }
        return response;
    }

    public void DoSomethingWithContent(T content) {}

    public void DoSomethingWithContent(IEnumerable<T> content) {}
}
Run Code Online (Sandbox Code Playgroud)

像这样使用......

只要响应内容值是类型T, 但有时它是IEnumerable<T>,并且在这种情况下TryGetContentValue()将返回false,因为T它不是IEnumerable<T>.所以我创建了一个重载,DoSomethingWithContent但我正在努力找出一种有效的方法来动态转换或声明content为正确的类型,以便调用正确的重载.

回答

我找了recursive答案,但我想发布完整的方法供参考:

public class MyClass<T> {

    HttpResponseMessage Modify(HttpResponseMessage response) {
        object content;
        if(response.TryGetContentValue(out content)) {
            if(content is IEnumerable<T>)
                DoSomethingWithContent((IEnumerable<T>)content);
            else
                DoSomethingWithContent((T)content);
        }
        return response;
    }

    public void DoSomethingWithContent(T content) {}

    public void DoSomethingWithContent(IEnumerable<T> content) {}
}
Run Code Online (Sandbox Code Playgroud)

rec*_*ive 7

您可以使用它is来确定要使用的案例.

if (content is IEnumerable<T>)
    DoSomethingWithContent((IEnumerable<T>)content);
else
    DoSomethingWithContent(content);
Run Code Online (Sandbox Code Playgroud)

如果你感觉很时髦,你可以通过强制转换来使用运行时绑定器,但不建议这样做.

DoSomethingWithContent((dynamic)content);
Run Code Online (Sandbox Code Playgroud)