0

We are writing a proxy generator using CodeDom and it appears that generic types in a recursive constraint are not being generated.

The code in question should just pass the constraint through as it is:

    void AddGenericConstraints(CodeTypeDeclaration generatedType, Type type)
    {
        var genericTypes = type.GetGenericArguments();

        foreach (var genericType in genericTypes)
        {
            var codeTypeParameter = new CodeTypeParameter(genericType.Name);
            if (genericType.IsGenericParameter)
            {
                // Get the constraints if the constraint is of user defined type
                var genericParameterConstraints = genericType.GetGenericParameterConstraints();
                foreach (var constraint in genericParameterConstraints)
                {
                    if (!string.Equals(constraint.Name, "ValueType"))
                    {
                        codeTypeParameter.Constraints.Add(constraint);
                    }
                }
            }

            generatedType.TypeParameters.Add(codeTypeParameter);
        }

But the input:

interface ISomething<T, out TSelf> where TSelf : ISomething<T, TSelf>
{
}

Produces the output (which does not compile):

interface ISomething<T, TSelf> where TSelf : ISomething<, >
{
}
4

1 回答 1

1

由于未知的原因,Add方法不使用类型参数名称,然后将其作为Type类型传递,但它会从字符串生成它们。显然区别在于CodeTypeReference类构造函数(这是Constraints集合中的最终项目类型)。所以

codeTypeParameter.Constraints.Add(constraint.ToString());

应该给你一个预期的结果。

于 2013-08-07T07:24:44.627 回答