使用 .NET CodeDOM 在一条语句中声明并初始化字段
我想使用 CodeDOM 在一条语句中声明和初始化我的静态字段。 我怎样才能做到这一点?
// for example
public static int MyField = 5;
我似乎可以弄清楚如何声明静态字段,并且可以稍后设置它的值,但我似乎无法获得上述效果。
@lomaxx, 不,我只想要静态。 我不想要常量。 该值可以改变。 我只是想要一举声明和初始化的简单性。 就好像 Codedom 世界里的一切都很简单。 每个类型名称的长度都超过 20 个字符,最终您将构建这些巨大的表达式树。 看得我眼睛都瞪出来了 多亏了 resharper 的重新格式化,我才能活到今天。
I want to use CodeDOM to both declare and initialize my static field in one statement. How can I do this?
// for example
public static int MyField = 5;
I can seem to figure out how to declare a static field, and I can set its value later, but I can't seem to get the above effect.
@lomaxx,
Naw, I just want static. I don't want const. This value can change. I just wanted the simplicity of declaring and init'ing in one fell swoop. As if anything in the codedom world is simple. Every type name is 20+ characters long and you end up building these huge expression trees. Makes my eyes bug out. I'm only alive today thanks to resharper's reformatting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你想要的是 const 而不是 static。 我假设您想要的是静态只读的效果,这就是为什么您总是希望该值为 5。
在 C# 中,常量的处理方式与只读静态完全相同。
来自 c# 文档:
I think what you want is a const rather than static. I assume what you want is the effect of having a static readonly which is why you always want the value to be 5.
In c# consts are treated exactly the same as a readonly static.
From the c# docs:
创建 CodeMemberField 实例来表示静态字段后,您可以将 InitExpression 属性分配给要用于填充字段的表达式。
Once you create your CodeMemberField instance to represent the static field, you can assign the InitExpression property to the expression you want to use to populate the field.
Omer van Kloeten 的这篇文章似乎做了什么你要。 请注意,输出包含以下行:
This post by Omer van Kloeten seems to do what you want. Notice that the output has the line: