Anonymous classes in C#

孤人 提交于 2020-01-07 04:14:05

问题


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.

The code should be like this

Class MyClass
{
    Class
    {
        String string1;
        String string2;

        void MyMethod();
    } Strings;
}

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

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


回答1:


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() {}
    }
}

You can then call: MyClass.Strings.string1 = "Hell, world!";




回答2:


This way I can elegantly group my code.

I don't how can this help you to elegantly group your code, but there is no such thing in C#. There are anonymous classes but they only work in local scopes:

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

And you can't add methods to them.

The closest thing you can get to is an inner class/struct:

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

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



回答3:


I agree Sweeper. This functionality adds just cluttering code. You should consider to make your code as easy as possible to understand. This means if you feal that you want to group your code, giving every group it´s own functionality, why not make this group a class and give it a name that directly reflects what its purpose is.

What you can do is use an anonymous class which in C# doesn´t implement any interface but just derives from object:

var a = new { MyMember = 1, MyFunc = new Func<int>(() => 1) };

now you can invoke both members of this type:

Console.WriteLine(a.MyMember);
var retVal = a.myFunc();

But does this make your code any better in a way that it´s easier to understand what it does? I doubt so. Give your instances - even when used only once - a name that describes what their intention - the idea behind - is. Don´t make it hard for others to understand your code by cryptifying it.

Apart from this you can restrict the use of your class to be private by nesting it within another one:

public class MyClass
{
    private class Strings { /* ... */ }
}

Now your class is just visible to itself and within MyClass (and in other classes that are nested in MyClass of course). This makes it impossible to access the class from the outside like so:

var strings = new MyClass.Strings();


来源:https://stackoverflow.com/questions/44259648/anonymous-classes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!