【问题标题】:Why is AssemblyQualifiedName of anonymous type not always the same?为什么匿名类型的 AssemblyQualifiedName 并不总是相同?
【发布时间】:2021-03-04 13:39:31
【问题描述】:

我试图从 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,也会发生同样的事情。

【问题讨论】:

    标签: c# .net reflection system.reflection


    【解决方案1】:

    问题是这样的代码

    var x = new { SomeString = "" };
    

    创建一个类似的类型

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

    所以x.GetType().AssemblyQualifiedName 返回包含泛型类型信息的类型名称。 要让它工作,您需要调用 GetGenericTypeDefinition() 以摆脱泛型类型信息。

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

    【讨论】:

    • 谢谢,但是为什么从 assembly.GetTypes() 返回的类型不返回相同的 AssemblyQualifiedName(带有泛型类型信息)?我相信如果我使用 GetGenericTypeDefinition() 我将找不到我需要的封闭泛型类型 - 还是我误解了你?
    • assembly.GetTypes() 返回所有已定义类型的列表。如果是泛型类型,例如List&lt;T&gt; 它将包含 type List&lt;T&gt; 但不包含派生类型 List&lt;int&gt;
    • 哦,是的,当然。我误以为在程序集中也定义了匿名类型的封闭形式。现在我看到他们显然不是,而且这没有任何意义:)
    • 忘记标记为答案,抱歉,现在完成:)
    猜你喜欢
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多