c# - 将 TypeOf "List<int>"与 "System.Collections.Generic.List<int>"进行比较

标签 c# reflection roslyn

我正在构建一个代码重构工具,在该工具中,我使用来自 Roslyn API 的标记/节点获得两种变量类型。

我需要比较和验证这两种类型是否相同。 其他一些问题,例如 this这在你有对象的情况下有效,但是在这种情况下我需要使用字符串并比较类型。这是我的方法,它适用于 typeName = "int" , 然而当typeName="List<int>"我得到 null

 public static Type GetType(string typeName)
    {
        string clrType = null;

        if (CLRConstants.TryGetValue(typeName, out clrType))
        {
            return Type.GetType(clrType);
        }


        var type = Type.GetType(typeName);

        if (type != null) return type;
        foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
        {
            type = a.GetType(typeName);
            if (type != null)
                return type;
        }
        return null;
    }
    private static Dictionary<string, string> CLRConstants { get{
            var dct =  new Dictionary<string, string>();
            dct.Add("int", "System.Int32");
            return dct;

        } }

最佳答案

您可以通过以下代码获取并检查所有可能的程序集类型。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var b in a.GetTypes())
                {
                    Console.WriteLine(b.FullName);
                }
            }
        }
    }
}

在打印的列表中有

System.Collections.Generic.List`1

这是为了

List<T> 

类型。 如果您想要您的确切需求,那就是

List<int>

你必须写

System.Collections.Generic.List`1[System.Int32]

所以你的代码将像这样工作:

public static Type GetType(string typeName)
{
    string clrType = null;

    if (CLRConstants.TryGetValue(typeName, out clrType))
    {
        return Type.GetType(clrType);
    }

    var type = Type.GetType(typeName);

    if (type != null) return type;
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = a.GetType(typeName);
        if (type != null)
            return type;
    }
    return null;
}
private static Dictionary<string, string> CLRConstants { 
    get{
            var dct =  new Dictionary<string, string>();
            dct.Add("int", "System.Int32");
            dct.Add("List<int>", "System.Collections.Generic.List`1[System.Int32]");
            return dct;
    } 
}

关于c# - 将 TypeOf "List<int>"与 "System.Collections.Generic.List<int>"进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53941314/

相关文章:

c# - C# 8 默认接口(interface)实现是否允许多重继承

reflection - WinRT 反射 (C++/CX)

c# - 使用 Roslyn 排序构造函数参数

c# - lambda 表达式中的枚举的编译方式不同;重载分辨率改进的结果?

c# - 使用 Roslyn 确定字段是否可序列化

c# - 如何获取字符串中的向量位置并将其存储为整数?

c# - 问号在 MVC 中意味着什么?

c# - 这个 .tlh 文件是否正确,如果不正确,我该如何生成正确的文件?

reflection - F# 相当于 C# typeof(IEnumerable<>)

java - 如何实现类型参数是参数化类型的约束