简体   繁体   English

c# 结构循环引用通过泛型

[英]c# struct cycled reference via generic

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.此外,当定义 2 个结构并且每个结构都具有另一个的字段类型时,问题实际上是相同的。

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.此代码编译良好并生成 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.当我尝试加载 dll 时,我得到“无法加载一个或多个请求的类型..”并仅列出具有上述关系的那些类型。 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.我还注意到,只要我有这种循环的泛型类型,dotnet 测试资源管理器就找不到任何测试,但我认为这是同一个问题。

EDIT:编辑:

The above code can be compiled into a.dll file.上面的代码可以编译成一个.dll文件。 Then, from another project I am using System.Runtime.Loader to dynamically load the dll:然后,从另一个项目中,我使用 System.Runtime.Loader 动态加载 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.在示例的最后一行,我得到了 ReflectionTypeLoadException。

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.到目前为止,解决此问题的成本被认为太高,无法证明这样做是合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM