IsAssignableFrom or AS?

aba*_*hev 5 c# generics inheritance interface

I have next code:

private T CreateInstance<T>(object obj) // where T : ISomeInterface, class
{
    ...

    if (!typeof(T).IsAssignableFrom(obj.GetType())) { throw ..; }

    return (T)obj;
}
Run Code Online (Sandbox Code Playgroud)

Can it be replaced with this:

T result = obj as T;

if (result == null) { throw ..; }

return result;
Run Code Online (Sandbox Code Playgroud)

If not - why?

Dav*_*vy8 6

关于什么 if (!(bar is T)) { throw ..; }

或者,如果您不需要自己的异常消息,最简单的答案就是:

return (T)obj;
Run Code Online (Sandbox Code Playgroud)

如果它不能转换为InvalidCastException的原因将被抛出并且返回被忽略.除非您添加更多逻辑或自定义错误消息,否则无需进行检查并抛出自己的异常.


Den*_*sky 4

另一种变体:

private T CreateInstance<T>(object obj) where T : ISomeInterface // as OP mentioned above
{
    ...

    T result = obj as T;
    if (result == null)
        { throw ..; }
    else 
       return result;
}
Run Code Online (Sandbox Code Playgroud)