具有 init 块的 Java 匿名内部类的 C# 等效项

发布于 2024-07-13 02:11:50 字数 177 浏览 5 评论 0原文

在 Java 中,我喜欢使用诸如

List<String> list = new ArrayList<String>() {{add("foo");}};

Is there a way to do this in 1 line in C#, so?

In Java, i like to use constructs such as

List<String> list = new ArrayList<String>() {{add("foo");}};

Is there a way to do this in 1 line in C#, too?

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

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

发布评论

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

评论(4

燃情 2024-07-20 02:11:50

这称为集合初始值设定项,它是 C# 3.0 的一部分。

除了列表之外,您还可以初始化更复杂类型的集合,只要它们实现 IEnumerable 并为集合初始值设定项中的每个元素提供适当的 Add 方法即可。 例如,您可以像这样使用 DictionaryAdd(key, value) 方法:

var dict = new Dictionary<string, int> 
{ 
    {"first", 10 }, 
    {"second", 20 }
};

更多详细信息可以参见《C# 深度学习》第 8 章,可以从曼宁的网站免费下载。

This is called a collection initializer and it's part of C# 3.0.

As well as lists, you can initialize collections of more complicated types, so long as they implement IEnumerable and have approprate Add methods for each element in the collection initializer. For example, you can use the Add(key, value) method of Dictionary<TKey, TValue> like this:

var dict = new Dictionary<string, int> 
{ 
    {"first", 10 }, 
    {"second", 20 }
};

More details can be found in chapter 8 of C# in Depth, which can be downloaded free from Manning's web site.

十六岁半 2024-07-20 02:11:50

我认为你想要的是一个数组初始值设定

List<string> list = new List<string>() { "foo" };

项多个项目应该以逗号分隔

List<string> list = new List<string>() { "foo","bar","bas"};

I think what you want is an array initializer

List<string> list = new List<string>() { "foo" };

Multiple items should be comma-separated

List<string> list = new List<string>() { "foo","bar","bas"};
怪我闹别瞎闹 2024-07-20 02:11:50

您可以在 .NET 3.5 中设置属性值:

List<string> list = new List<string> () { Property = Value, Property2 = Value2 };

或者初始化数组:

List<string> list = new List<string> () { "value1", "value2" };

但是,您不能以这种方式调用方法。

You can do it in .NET 3.5 to set property values:

List<string> list = new List<string> () { Property = Value, Property2 = Value2 };

Or to initialize an array:

List<string> list = new List<string> () { "value1", "value2" };

You can't call methods this way, however.

梦里人 2024-07-20 02:11:50

如果您只需要处理将对象添加到集合中,那么集合初始值设定项工作得很好,但如果您需要执行更多静态初始化,则可以使用称为静态构造函数的东西,其工作方式与 java 中的静态初始值设定项

相同href="http://www.c-sharpcorner.com/UploadFile/cupadhyay/StaticConstructors11092005061428AM/StaticConstructors.aspx" rel="nofollow noreferrer">这的格式很差,但似乎覆盖了它

If you just need to deal with adding objects to a collection, then collection initializers work great, but if you need more static initialization to be performed, you can use something called a static constructor that works the same as a static initializer in java

This has poor formatting but seems to cover it

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