为什么匿名类型的 AssemblyQualifiedName 不总是相同的?

Why is AssemblyQualifiedName of anonymous type not always the same?

我试图通过 AssemblyQualifiedName 从程序集集合中查找匿名类型,但尽管匿名类型存在于扫描的程序集中,但未找到。 GetTypes() 似乎 return 类型与其他 AssemblyQualifiedNames。

为什么 AssemblyQualifiedNames 不同,我该怎么做才能在给定的程序集中找到正确的类型?

    [Fact]
    public void AnonTypes()
    {
        var entity = new { SomeString = "Asger" };
        var type = entity.GetType();
        var assemblyQualifiedName = type.AssemblyQualifiedName;

        var types = type.Assembly.GetTypes()
            .Where(x => x.AssemblyQualifiedName == assemblyQualifiedName)
            .ToList();

        types.Count.ShouldBe(1);
    }

请注意,Type.GetType(assemblyQualifiedName) 可找到类型,但我不能使用此方法,因为我并不总是有 AssemblyQualifiedName,而是要搜索其他一些限定符。

另请注意,如果实体是 ValueTuple,也会发生同样的事情。

问题是这样的代码

var x = new { SomeString = "" };

创建类似

的类型
public class AnonymousType0<T> 
{
    public T SomeString { get; set; }
}

所以 x.GetType().AssemblyQualifiedName returns 包含通用类型信息的类型的名称。 要使其正常工作,您需要调用 GetGenericTypeDefinition() 来删除通用类型信息。

例如,类型 List<int> 的 AssemblyQualifiedName 类似于 System.Collections.Generic.List``1[[System.Int32, ...]], ...,但在 assembly.GetTypes() 中,您会发现 System.Collections.Generic.List``1, ....