2016-08-18 67 views
2

下面的代码编译在两个VS2013和VS2015,各种版本的.NET Framework 2.0至4.6.1时引发一个TypeLoadException,但是当被执行时将引发System.TypeLoadException:非常简单的代码编译,但执行

namespace Test 
{ 
    struct Foo<T> 
    { 
    } 

    struct Bar<U> 
    { 
     Foo<Bar<U>> foo; 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var x = new Bar<int>(); 
     } 
    } 
} 

但是,如果Foo或Bar从结构更改为类,它将运行。我试图理解为什么这不适用于两个结构。为什么这个代码失败?

异常消息是:

"System.TypeLoadException occurred Message: A first chance exception of type 'System.TypeLoadException' occurred in mscorlib.dll Additional information: Could not load type 'Test.Bar`1' from assembly 'scratch, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'."

+1

的[在结构VS类使用泛型]可能的复制(HTTP://计算器.com/questions/13731798/generics-used-in-struct-vs-class) – MethodMan

+1

TypeLoadException的消息是什么? –

+0

异常消息是:“发生了System.TypeLoadException异常 消息:mscorlib.dll中发生了类型'System.TypeLoadException'的第一次机会异常 其他信息:无法从程序集'scratch'加载类型'Test.Bar'1, Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'。“ –

回答

1

你不能用环形类型

类似的问题创建结构:

struct Foo 
{ 
    Bar bar; 
} 

struct Bar 
{ 
    Foo foo; 
} 

struct Foo 
{ 
    Foo foo1; 
    Foo foo2; 
} 

类使用refe分配办法和工作正常

通用逻辑有同样的问题,但只在运行时(IL-编译)

struct Foo<T>建议使用美孚,结构内部的T型生产类型的错误,但这种产品在结构布局的循环

如果你真的使用T型,它也产生一个编译器错误:

struct Foo<T> 
{ 
    T demo; // CS0523 
} 

struct Bar<U> 
{ 
    Foo<Bar<U>> foo; // CS0523 
} 
相关问题