C#中的匿名类 [英] Anonymous classes in C#

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

问题描述

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

In C++ I can declare a fully functional anonymous class inside a piece of code where it's needed so that I don't have to declare it if I need it only once.

代码应该是这样的

Class MyClass
{
    Class
    {
        String string1;
        String string2;

        void MyMethod();
    } Strings;
}

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

And call it the members with MyClass.Strings.string1, MyClass.Strings.MyMethod() and so on. This way I can elegantly group my code.

在C#中是否可以做同样的事情?

Is there a way to do the same thing in C#?

推荐答案

尝试将内部类设为静态。这样,您将能够使用所描述的语法:

Try making the inner class static. That way you will be able to use the syntax you describe:

class MyClass {
    public static Strings {
        public static string string1;
        public static string string2;
        public static void MyMethod() {}
    }
}

然后您可以调用: MyClass.Strings.string1 =地狱,世界!;

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

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