[英]Resolve generics with Mono.Cecil
I have a hierarchy of types of unknown depth. 我有一个未知深度类型的层次结构。 But at the and, this hierarchy implements IPlugin<T>
or IPlugin<T1, T2>
interface (from the other .dll
). 但是在and处,此层次结构实现IPlugin<T>
或IPlugin<T1, T2>
接口(来自其他.dll
)。 How can I resolve <T>
or <T1, T2>
generics from IPlugin
? 如何从IPlugin
解析<T>
或<T1, T2>
泛型? This generics position can be random on the top class. 该类属位置在顶级产品上可能是随机的。
Example: 例:
// other .dll
interface IPlugin<T> {}
interface IPlugin<T1, T2> {}
// my code
class PluginBase<T1, T2>: IPlugin<T2, T1> {}
class AnotherClass<T1, T2, T3>: PluginBase<T3, T1> {}
class Plugin: AnotherClass<string, int, char> {}
From this example i expect string
and char
type definition. 从这个例子中,我期望string
和char
类型定义。
Here is an example , but it uses the position of the arguments and there is no traversal of the hierarchy. 这是一个示例 ,但它使用参数的位置,并且没有遍历层次结构。
The result is a code like this: 结果是这样的代码:
public class TypeWithSelfReference
{
public TypeWithSelfReference(TypeDefinition type, TypeReference reference)
{
Type = type;
Reference = reference;
}
public TypeDefinition Type { get; }
public TypeReference Reference { get; }
public void Deconstruct(out TypeDefinition type, out TypeReference derived)
{
type = Type;
derived = Reference;
}
}
public static List<TypeWithSelfReference> GetHierarchy(this TypeDefinition typeDefinition, Func<TypeDefinition, bool> breakCondition)
{
var hierarchy = new List<TypeWithSelfReference>();
foreach (var definition in typeDefinition.Traverse())
{
hierarchy.Add(new TypeWithSelfReference(definition, null));
if (breakCondition(definition))
break;
}
hierarchy.Reverse();
for (var i = 0; i < hierarchy.Count - 1; i++)
{
hierarchy[i] = new TypeWithSelfReference(hierarchy[i].Type, hierarchy[i + 1].Type.BaseType);
}
return hierarchy.Take(hierarchy.Count - 1).ToList();
}
private static TypeReference ResolveGenericParameter(IEnumerable<TypeWithSelfReference> hierarchy, GenericParameter parameter)
{
foreach (var (type, reference) in hierarchy)
{
foreach (var genericParameter in type.GenericParameters)
{
if (genericParameter != parameter)
continue;
var nextArgument = ((GenericInstanceType) reference).GenericArguments[genericParameter.Position];
if (!(nextArgument is GenericParameter nextParameter))
return nextArgument;
parameter = nextParameter;
break;
}
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.