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

问题描述

我试图从 AssemblyQualifiedname 的程序集集合中查找匿名类型,但尽管匿名类型存在于扫描的程序集中,但未找到。 GetTypes() 似乎返回具有其他 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 返回包含泛型类型信息的类型名称。 要使其正常工作,您需要调用 GetGenericTypeDefinition() 以删除通用类型信息。

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