gpt4 book ai didi

c# - C# 中的匿名类

转载 作者:行者123 更新时间:2023-12-05 09:18:30 27 4
gpt4 key购买 nike

在 C++ 中,我可以在一段代码中需要的地方声明一个功能齐全的匿名类,这样我就不必在只需要一次的情况下声明它。

代码应该是这样的

Class MyClass
{
Class
{
String string1;
String string2;

void MyMethod();
} Strings;
}

并以MyClass.Strings.string1MyClass.Strings.MyMethod()等调用成员。这样我就可以优雅地对我的代码进行分组。

有没有办法在 C# 中做同样的事情?

最佳答案

This way I can elegantly group my code.

我不知道这如何帮助您优雅地对代码进行分组,但 C# 中没有这样的东西。有匿名类,但它们只在本地范围内工作:

// inside a method:
var obj = new { String1 = "Hello", String2 = "World" };

而且您不能向它们添加方法。

最接近的是内部类/结构:

class MyClass
{
class MyStrings
{
String string1;
String string2;

void MyMethod() { ... }
}
MyStrings Strings;
}

关于c# - C# 中的匿名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44259648/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com