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等?
考虑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类设置的先例,除非有针对它的令人信服的论据.