首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeLoadException未被尝试/捕获捕获

TypeLoadException未被尝试/捕获捕获
EN

Stack Overflow用户
提问于 2010-07-27 18:34:52
回答 1查看 1.9K关注 0票数 3

为了演示目的,我试图重新创建一个TypeLoadException,所以我有一个可笑的愚蠢的库设置,如下所示:

代码语言:javascript
复制
TestProject --> TheLibrary [1.0]
            \-> ProxyForV2 -> TheLibrary [2.0]

TheLibrary版本1具有以下相关接口:

代码语言:javascript
复制
public interface IConsistentThing
{
    int ConsistentProperty { get; set; }
}

public interface IShrinkingThing
{
    int RemovedProperty { get; set; }
}

虽然TheLibrary接口的第2版看起来像:

代码语言:javascript
复制
public interface IConsistentThing
{
    int ConsistentProperty { get; set; }
}

public interface IShrinkingThing
{ }

ProxyForV2有这个类,它实现了2.0版本的IShrinkingThing

代码语言:javascript
复制
public class ShrinkingThingImpl : IShrinkingThing
{
    public int ConsistentProperty { get; set; }
}

因此,在TestProject中,如果有人试图分配一个ProxyForV2.ShrinkingThingImpl,我希望会导致一个ProxyForV2.ShrinkingThingImpl,因为接口的第一个版本有一个不是由第二个版本实现的属性。为了证明这一点,我有一个单元测试,看起来如下:

代码语言:javascript
复制
[TestMethod]
public void ShrinkingThingBreaks()
{
    try
    {
        IShrinkingThing thing = new ProxyForV2.ShrinkingThingImpl();

        Assert.Fail("This should have caused a TypeLoadException");
    }
    catch (TypeLoadException)
    {
        //  valid
    }
}

我的问题是:这个单元测试失败了。但不是因为我的Assert.Fail,正如我所期望的那样。测试输出如下所示:

测试方法TestProject.LoadTester.ShrinkingThingBreaks抛出异常: System.TypeLoadException:方法'get_RemovedProperty‘类型为'ProxyForV2.ShrinkingThingImpl’,来自程序集'ProxyForV2,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null‘没有实现。

因此,抛出一个TypeLoadException,尽管它可能抛出的唯一位置是在一个带有catch (TypeLoadException)try块中,但异常拒绝被捕获。除此之外,即使我使用了catch,单元测试失败时也会出现与前面相同的错误:

代码语言:javascript
复制
[TestMethod]
public void ShrinkingThingBreaks()
{
    try
    {
        IShrinkingThing thing = new ProxyForV2.ShrinkingThingImpl();

        Assert.Fail("This should have caused a TypeLoadException");
    }
    catch
    {
        //  valid
    }
}

怎么一回事?显然,这是一个完全人为的场景,但我仍然想知道发生了什么,这样就可以在运行时避免这个错误,或者至少在发生这种情况时处理这个错误(是的,我知道最终的解决方案是确保所有库版本都是相同的)。

最糟糕的是,任何对类的访问(如typeof(ProxyForV2.ConsistentThingImpl)ProxyForV2.ConsistentThingImpl.SomeStaticFunction() )都会导致这个不可捕获的TypeLoadException,因此很明显,问题起源于.NET试图加载类时,而不是任何赋值。

我缓解这个问题的唯一想法是尝试在一个不同的应用程序域中加载类型,这样它就不会干扰,然后做一些疯狂的反射来查看接口是否与实现兼容,但这似乎是完全的和完全的过度。

总之:为什么要以“正常”的方式解决这个问题似乎是不可能的?我如何在运行时解决这样的问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-07-27 19:05:35

在使用它们的方法开始执行之前加载类型。要做到这一点,您需要:

代码语言:javascript
复制
[TestMethod]
public void ShrinkingThingBreaks()
{
    try
    {
        InnerShrinkingThingBreaks();

        Assert.Fail("This should have caused a TypeLoadException");
    }
    catch
    {
        //  valid
    }
}

[MethodImpl(MethodImplAttributes.NoInlining)]
private void InnerShrinkingThingBreaks()
{
        IShrinkingThing thing = new ProxyForV2.ShrinkingThingImpl();
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3346740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档