C# 在方法中声明一个类或结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10718653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:58:14  来源:igfitidea点击:

Declare a class or struct inside a method

c#.net

提问by Thorin Oakenshield

In C#, is it possible to declare a class or struct inside a method, as in C++?

在 C# 中,是否可以像在 C++ 中一样在方法中声明类或结构?

e.g. C++:

例如 C++:

void Method()
{
   class NewClass
   {
   } newClassObject;
}

I have tried, but it's not allowing me to do so.

我试过了,但它不允许我这样做。

回答by erikkallen

You can create an anonymous type like so:

您可以像这样创建匿名类型:

var x = new { x = 10, y = 20 };

but other than that: no.

但除此之外:没有。

回答by mattytommo

You can declare them inside a classas your question states, but not inside a methodas your question title states. Something like:

您可以在类中声明它们作为您的问题所述,但不能在您的问题标题所述的方法中声明。就像是:

public class MyClass
{
    public class MyClassAgain
    {
    }

    public struct MyStruct
    {
    }
}

回答by Sleiman Jneidi

Yes, it is possible to declare a classinside a classand these are called inner classes

是的,可以声明一个classinside aclass并且这些被称为inner classes

public class Foo
{
    public class Bar
    { 

    }
 }

and this how you can create an instance

以及如何创建实例

Foo foo = new Foo();
Foo.Bar bar = new Foo.Bar();

And within a method you can create an object of anonymoustype

在一个方法中,你可以创建一个anonymous类型的对象

void Fn()
{
 var anonymous= new { Name="name" , ID=2 };
 Console.WriteLine(anonymous.Name+"  "+anonymous.ID);
}