.net 在方法内部对类或结构进行解密

velaa5lx  于 12个月前  发布在  .NET
关注(0)|答案(6)|浏览(103)

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

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

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

xesrikrc

xesrikrc1#

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

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

但除此之外号

omqzjyyz

omqzjyyz2#

是的,可以在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);
}
eqoofvh9

eqoofvh93#

你可以在一个中声明它们作为你的问题状态,但不能在一个方法中声明它们作为你的问题标题状态。例如:

public class MyClass
{
    public class MyClassAgain
    {
    }

    public struct MyStruct
    {
    }
}
nzk0hqpo

nzk0hqpo4#

在C#中,此时方法中没有局部类,但有一些解决方法:
1.使用预编译器将类描述移到方法之外(Roslyn在这里会很有帮助)
1.如果你已经有一个接口,你可以使用NuGet包ImportuInterface在你的方法中创建一个本地类
1.使用本地方法来模拟类:

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);
     }
 }

上面的打印:十六二十一十十三。

kiayqfof

kiayqfof5#

今天,您可以使用元组字段名称https://learn.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" }));
}
ubby3x7f

ubby3x7f6#

有趣的是,运行时确实有必要支持本地类型:System.Type类包含一个DeclaringMethod成员,当类型是在方法中声明的匿名类型时,将设置该成员。但是该语言不支持在方法中声明元组和匿名类型以外的任何东西。
这是一个遗憾,因为方法局部类型在测试中非常有用,为了:
1.保持每种类型靠近使用它的地方
1.避免污染测试类的命名空间
1.防止一个测试方法意外使用另一个测试方法要使用的类型。
为了实现上面列出的三个目标中的两个,我做了以下事情:
1.我将测试类声明为partial
1.我将每个测试方法放在测试类的单独部分中。(所有零件都在同一文件中。)
1.如果语言允许,在测试方法中声明的类型可以在测试类的各个部分之间声明,本质上就在它们所属的每个方法之前。

相关问题