CodeDom 泛型类型约束

发布于 2024-07-11 18:05:00 字数 504 浏览 6 评论 0原文

有没有办法用 CodeDom 生成类约束。

因为当我使用

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

生成的代码

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

之类的东西时,我发现的最佳解决方法是在类之前使用前导空格

genericParam.Constraints.Add(" class");

但这似乎充其量是一种解决方法。

Is there a way to generate a class constraint with 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

熊抱啵儿 2024-07-18 18:05:00

似乎没有直接的方法来指定该约束。 对于“struct”约束都不是。

对于“T : new()”约束,请使用标志 HasConstructorConstraint

对于其余部分,请使用 CodeTypeReference,如 此 msdn 示例

It seems that there is no straigntforward way to specify that constraint. Neither for the "struct" constraint.

For the "T : new()" constraint use the flag HasConstructorConstraint

For the rest use CodeTypeReference as in this msdn example.

呆° 2024-07-18 18:05:00

我还使用零宽度空间("\x200Bclass")而不是普通空间。 然后我将最终字符串中的它替换为空字符串: .Replace("\x200B", string.Empty);

I also use zero-width space ("\x200Bclass") instead of normal space. Then I replace it in final string with empty string: .Replace("\x200B", string.Empty);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文