System.InvalidCastException:无法将类型为“System.Object”的对象强制转换为“System.IO.StreamWriter”

时间:2013-11-06 18:48:48

标签: c# ssis .net-3.0

我尝试将Object变量转换为StreamWriter。但是,它不起作用。这是什么错误?

StreamWriter file = (StreamWriter) myObject;

4 个答案:

答案 0 :(得分:3)

myObject的值不是(可转换为)StreamWriter。

答案 1 :(得分:3)

试试这个:

if (myObject is StreamWriter) 
{
    var file = (StreamWriter) myObject as StreamWriter;
}

答案 2 :(得分:2)

我愚蠢的另一个时刻。我已经注释掉了这一行 - Object myObject = Dts.Variables [" yourStreamWriterHere"]。所以,myObject里面什么都没有。那里有空吗?在Java中它是。此外,java为您提供了一个很好的nullPointerException。但是,visual studio为您提供了一个神秘的" Micro $ lop™:无法找到错误原因。联系 Billy 以获取更多帮助。请妥善保管您的信用卡以防万一。呼叫中心等待时间有所不同"。只是很烦人。

无论如何,你得到的真正错误是 -

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'System.IO.StreamWriter'.
   at ST_ffrrefr939322939392dfr.csproj.ScriptMain.Main()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

答案 3 :(得分:1)

转换之前,请检查是否可以使用StreamWriter关键字将其转换为is对象,如下所示:

if(myObject is StreamWriter)
{
//can be cast
}
else
{
//can not be cast
}