简体   繁体   English

CodeDom泛型类型约束

[英]CodeDom generic type constraint

Is there a way to generate a class constraint with CodeDom. 有没有办法用CodeDom生成类约束。

Because when I use something like 因为当我使用类似的东西

var method = new CodeMemberMethod();
var genericParam = new CodeTypeParameter("InterfaceType");
genericParam.Constraints.Add("class");
method.TypeParameters.Add(genericParam);

the generated code is like 生成的代码就像

private InterfaceType GetImpl<InterfaceType>()
    where InterfaceType : @class
{
}

The best workaround i found is to use a leading whitespace before the class 我发现最好的解决方法是在课前使用前导空格

genericParam.Constraints.Add(" class");

But this seems to be at best a workaround. 但这似乎充其量只是一种解决方法。

It seems that there is no straigntforward way to specify that constraint. 似乎没有直接的方法来指定该约束。 Neither for the "struct" constraint . 对于“struct”约束都没有。

For the "T : new()" constraint use the flag HasConstructorConstraint 对于“T:new()”约束,使用标志HasConstructorConstraint

For the rest use CodeTypeReference as in this msdn example . 对于其余部分,请使用此msdn示例中的 CodeTypeReference。

I also use zero-width space ( "\\x200Bclass" ) instead of normal space. 我也使用零宽度空间( "\\x200Bclass" )而不是普通空间。 Then I replace it in final string with empty string: .Replace("\\x200B", string.Empty); 然后我在最后一个字符串中用空字符串替换它: .Replace("\\x200B", string.Empty);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM