在VS 2008中即时窗口的特殊行为
-
27-09-2019 - |
题
今天,一些奇特的事,而在VS 2008调试我将给一小段代码
List<IPageHandler> myPageList = TaskSOM.PageList;
if( myPageList != null && myPageList.Count > 0 )
{
PageHandler aPage = myPageList[0] as PageHandler;
...; // Some more code below
}
当运行类型转换失败和APAGE成为空的应用(这是用于调试的原因)。因此,所有的一切使用vaiable失败的码。但是调试过程中myPageList的第一个元素是在行动上页面处理器。当我在即时窗口中执行线
PageHandler aPage = myPageList[0] as PageHandler;
APAGE变量具有正确的值。但是,如果调试器移动到该行并执行我得到一个空。由于保密我无法共享整个代码。但是,有没有人面对过去的即时窗口这样的问题。是否有任何关于如何材料立即窗口作品。
解决方案
这将在您的不的要使用的为的操作代码一个很好的例子。显然,你不能投失败,或者你会包括一个空测试,做一些有意义的事如果转换失败。
使用一个真实的铸造。你会得到一个异常信息,让您更好的提示,为何投失败:
PageHandler aPage = (PageHandler)myPageList[0];
例外是你的朋友,不要回避他们。瞎猜:当你在一个线程中使用COM对象和COM服务器不支持封送处理这可能发生。如果是这样的话,那么异常信息会告诉你。
其他提示
因此,这里的全部细节。唯一的例外是
[A]SimpleClassLib.PageHandler cannot be cast to [B]SimpleClassLib.PageHandler. Type A originates from 'SimpleClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'D:...\bin\SimpleClassLib.dll'. Type B originates from 'SimpleClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'D:...\bin\Debug\SimpleClassLib.dll'
在显影剂上述[A] d ... \ BIN \调试\ SimpleClassLib.dll所以本申请的一个部分从[A]创建页面处理器实例并填充列表,另一部分试图从键入[B]铸造到页面处理器。
下面的例子将容易引发此错误。希望这可以帮助别人。 这是一个简单的类库。建立这个作为DLL。
// SimpleClassLib.dll
namespace SimpleClassLib
{
public class Foo
{
string Prop1 { get { return "I am Foo!!"; } }
}
}
以下是控制台应用程序。该应用程序链接到SimpleClassLib等从VS 2008正常加载参考此外,它从另一个路径加载的实例。
// Separate console application App.exe
// Progoram.cs
using SimpleClassLib;
namespace App
{
class Program
{
List<object> myFooList;
Program()
{
myFooList = new List<object>();
Assembly a = Assembly.LoadFile(@"<differentpath>\SimpleClassLib.dll");
Type aFooType = a.GetType("SimpleClassLib.Foo");
ConstructorInfo aConstructor = aFooType.GetConstructor(new Type[] { });
myFooList.Add(aConstructor.Invoke(new object[]{}));
myFooList.Add(aConstructor.Invoke(new object[] { }));
myFooList.Add(aConstructor.Invoke(new object[] { }));
}
void DumpPeculiar()
{
for (int i = 0; i < myFooList.Count; i++)
{
// If one inspects the list in debugger will see a list of
// Foo but this Foo comes from a different load context so the
// following cast will fail. While if one executes the line
// f = myFooList[i] as Foo
// it will succeed
Foo f = myFooList[i] as Foo;
Foo f1 = (Foo)myFooList[i];
}
}
static void Main(string[] args)
{
Program p = new Program();
p.DumpPeculiar();
}
}
}