Home > Enterprise >  c# struct cycled reference via generic
c# struct cycled reference via generic

Time:12-01

When defining a struct it is clear that value of the struct field cannot be the stuct itself. Also, when defining 2 structs and each has a field type of the other, the problem is effectively the same.

But when instead of directly setting type one uses a generic over that type, why is this still a problem?

public struct Generic<T> { }
public struct Test1
{
  Generic<Test2> f;
}


public struct Test2
{
  Generic<Test1> f;
}

This code compiles fine and generates a dll. When I try to load the dll I get the 'Unable to load one or more of the requested types..' and lists only those types that have relationship described above. If I remove only one of the fields, then load is successfull. What is going on and how to fix this?

I also noticed that dotnet test explorer does not find any test as long as I have this cycled generic types, but I presume that it is the same problem.

EDIT:

The above code can be compiled into a .dll file. Then, from another project I am using System.Runtime.Loader to dynamically load the dll:

public static void Main(string[] args)
{ 
  var context = new AssemblyLoadContext("context");
  Assembly assembly = context.LoadFromAssemblyPath("path-to-dll");
  Type[] types = assembly.GetTypes();
}

On the last line of the example I get the ReflectionTypeLoadException.

CodePudding user response:

I agree, this should work. But it doesn't. It's a known issue with how the runtime loads types.

Fixing this issue would apparently require rewriting the core implementation of how types are loaded. Leading to significant changes in behaviour that could impact a large fraction of existing programs. So far the cost for fixing this issue is considered to be too high to justify doing it.

  • Related