【发布时间】:2021-09-14 07:58:30
【问题描述】:
我有一个类型参数值的字典:
ImmutableDictionary<string, ITypeSymbol> typeParameterValues;
如何使用 ITypeSymbol 替换这些类型参数:
例如。 List<T> -> List<string>(如果 T 是字符串)
例如。 Dictionary<K, V>.ValueCollection -> Dictionary<string, int>.ValueCollection(如果 K 是字符串,V 是整数)
到目前为止,我已经能够使用以下代码使第一个示例工作:
static ITypeSymbol SubstituteGenericArgs (ITypeSymbol type) => type switch {
ITypeParameterSymbol tps => typeParameterValues[tps.Name]
INamedTypeSymbol nts when nts.IsGeneric => nts.ConstructedFrom.Construct(
nts.TypeParameters.Select(SubstituteGenericArgs).ToArray()
),
INamedTypeSymbol ngts when !ngts.IsGeneric => ngts
};
我知道我可以做到nts.ContainingType,但问题是一旦我将正确的类型参数替换为包含类型,就无法使用我找到的新包含类型来获取原始类型。
【问题讨论】:
-
您能否格式化您的代码以使其更具可读性?
-
我尽力了。_
-
我的编辑有帮助吗?如果没有,请拒绝/恢复它们。
-
所以你问的是,当
nts.ContainingType.IsGeneric如何判断SubstituteGenericArgs(nts.ContainingType).GetMembers(nts.Name)中的哪一个与nts是同一成员?也许通过比较.OriginalDefinition?