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

时间:2012-05-23 11:04:00

标签: c# .net

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

e.g。 C ++:

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

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

4 个答案:

答案 0 :(得分:14)

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

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

但除此之外:没有。

答案 1 :(得分:9)

是的,可以在class内声明class,这些被称为inner classes

public class Foo
{
    public class Bar
    { 

    }
 }

以及如何创建实例

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

在方法中,您可以创建anonymous类型

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

答案 2 :(得分:7)

您可以在问题所述的中声明它们,但不能在问题标题所述的方法中声明。类似的东西:

public class MyClass
{
    public class MyClassAgain
    {
    }

    public struct MyStruct
    {
    }
}

答案 3 :(得分:2)

在 C# 中,此时方法中没有本地类,但有解决方法:

  1. 使用预编译器将类描述移到您的方法之外(Roslyn 在这里会有所帮助)

  2. 如果你已经有一个接口,你可以使用 NuGet 包 ImpromptuInterface 在你的方法中创建一个本地类

  3. 使用本地方法模拟一个类:

     class Program
     {
         static void Main(string[] args)
         {
             dynamic newImpl()
             {
                 int f1 = 5;
                 return new { 
                     M1 = (Func<int, int, int>)((c, d) => c + d + f1), 
                     setF1 = (Func<int,int>)( p => { var old = f1; f1 = p; return old; 
                            }) };
             }
             var i1Impl = newImpl();
             var i2Impl = newImpl();
             int res;
             res = i1Impl.M1(5, 6);
             Console.WriteLine(res);
    
             i1Impl.setF1(10);
    
             res = i1Impl.M1(5, 6);
             Console.WriteLine(res);
    
             res = i2Impl.M1(2, 3);
             Console.WriteLine(res);
    
             res = i1Impl.M1(1, 2);
             Console.WriteLine(res);
         }
     }
    

以上打印: 16,21,10,13 .

相关问题