34

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

例如 C++:

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

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

4

5 回答 5

28

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

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

但除此之外:没有。

于 2012-05-23T11:05:25.750 回答
14

是的,可以在 a 中声明 a classclass这些被称为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);
}
于 2012-05-23T11:10:36.643 回答
9

您可以在问题状态下在类中声明它们,但不能在问题标题状态下在方法中声明它们。就像是:

public class MyClass
{
    public class MyClassAgain
    {
    }

    public struct MyStruct
    {
    }
}
于 2012-05-23T11:07:43.770 回答
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 。

于 2021-05-06T08:32:36.937 回答
0

今天您可以使用元组字段名称 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples#tuple-field-names

喜欢

void GetData() {
List <(string h,int hideClm, double cw, HtColumns t)> k1 = new List<(string h, int hideClm, double cw, HtColumns t)>();
        k1.Add((h: "",0,cw:50, t: new HtColumns() { type = "text" }));
        k1.Add((h: "Record time",0, cw: 190, t: new HtColumns() { type = "text" }));
        k1.Add((h: "Partner",0, cw: 290, t: new HtColumns() { type = "text" }));
}
于 2022-01-10T08:12:51.630 回答