CodeDom中泛型类型约束 [英] CodeDom generic type constraint

查看:245
本文介绍了CodeDom中泛型类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来生成CodeDom中一类约束。

Is there a way to generate a class constraint with CodeDom.

由于我使用类似

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.

推荐答案

这似乎是有指定的约束没有straigntforward方式。无论对于结构的约束

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

有关的T:新的()限制使用标志 HasConstructorConstraint

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

对于剩下的使用CodeTypeReference如此MSDN例子

For the rest use CodeTypeReference as in this msdn example.

这篇关于CodeDom中泛型类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆