【问题标题】:Compare TypeOf "List<int>" to "System.Collections.Generic.List<int>"比较 TypeOf "List<int>" 和 "System.Collections.Generic.List<int>"
【发布时间】:2018-12-27 16:02:46
【问题描述】:

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

我需要比较和验证这两种类型是否相同。 其他一些问题,例如this,如果您有对象,则可以使用,但是在这种情况下我需要使用字符串并比较类型。这是我的方法,适用于typeName = "int",但是当typeName="List&lt;int&gt;" 我得到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;

        } }

【问题讨论】:

  • 这段代码有问题吗?您能否将edit 该信息纳入您的问题?
  • 如果 typeName 是 "List" 我得到空值
  • 您的意思是要首先意识到List&lt;...&gt; 是通用的,然后查找它,然后查找int 并构造List&lt;int&gt;?还是什么?
  • 这与我的问题完全无关,但是......你设置了我的强迫症,a 是一个糟糕的名字
  • @TheGeneral 将GetAssemblies 调用结果缩短为 3 个字母的标准方法看起来不专业...所以在 这种情况下 中的a 是可以的 :)

标签: c# reflection roslyn


【解决方案1】:

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

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;
    } 
}

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多