对于传入的Object并且需要强制转换为泛型参数,抛出什么是适当的异常?

mic*_*ael 4 c# generics casting exception

public IPredefinedInterface
{
    void DoSomething(Object obj);
}

public class MyClass<T> : IPredefinedInterface
{
    public void DoSomething(Object obj)
    {
        if (!(obj is T)) throw new ???

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

不知道这里适当的异常是什么... ArgumentException,InvalidCastException等?

Joh*_*ers 10

这是一个问题,所以ArgumentException.你还没有真正完成演员表,所以InvalidCastException不合适.


Ant*_*ram 5

考虑IList支持Add使用类型的操作的示例object.当通用实现时List<T>,您会获得ArgumentException无效类型.

var list = new List<int>();
var ilist = list as IList;
ilist.Add("A");
Run Code Online (Sandbox Code Playgroud)

结果:

ArgumentException:值"A"不是"System.Int32"类型,不能在此通用集合中使用.参数名称:value

在这样的例子中,我可能倾向于遵循BCL类设置的先例,除非有针对它的令人信服的论据.