我正在构建一个代码重构工具,在该工具中,我使用来自 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/