使用 .NET CodeDOM 在一条语句中声明并初始化字段

发布于 2024-07-04 14:20:52 字数 360 浏览 6 评论 0原文

我想使用 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 技术交流群。

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

发布评论

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

评论(3

↘紸啶 2024-07-11 14:20:53

我认为你想要的是 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:

Even though constants are considered
static members, a constant-
declaration neither requires nor
allows a static modifier.

往事随风而去 2024-07-11 14:20:52

创建 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.

一杆小烟枪 2024-07-11 14:20:52

Omer van Kloeten 的这篇文章似乎做了什么你要。 请注意,输出包含以下行:

private static Foo instance = new Foo();

This post by Omer van Kloeten seems to do what you want. Notice that the output has the line:

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