c#如何在具有多重返回的方法中使用Delegate



我不知道为什么这段代码不起作用。

  1. 控制台中只显示"a=1,b=2,c=3,d=4"
  2. 我的课。a没用。为什么

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace po
{
public delegate void godmode(int a, int b, out int c, out int d);
public class Class1
{
    public  int a;
    public int b;
    public int c;
}
public class Program
{
    Class1 myclass = new Class1();
    Program pro = new Program();
    // myclass.a didnt work

    static void go1(int a, int b, out int c, out int d)
    {
        c = a + b;
        d = (a + b) * 10;
    }
    static void go2(int a, int b, out int c, out int d)
    {
        c = a;
        d = b;
    }
    static void go3(int a, int b, out int c, out int d)
    {
        c = a * 100;
        d = b * 200;
    }

    static int outofgod(int a,out int result1,out int result2, godmode beaman)
    {
        int b = a*2;
        int c = a*3;
        int re1, re2;
        beaman(b,c,out re1,out re2);
         result1 = re1 * 10;
         result2 = re2;
    }

    static void Main(string[] args)
    {
        int a = 1;
        int b = 2;
        int c = 0;
        int d = 0;
        Console.WriteLine("a = {0}.....b = {1}..... c = {2}.... d = {3}",a,b,c,d);

        godmode mode1;
        godmode mode2;
        godmode mode3;
        mode1 = new godmode(go1);
        mode2 = new godmode(go2);
        mode3 = new godmode(go3);
        outofgod(a,out c,out d,mode1);
        Console.WriteLine("a = {0}.....b = {1}..... c = {2}.... d = {3}", a, b, c, d);
        outofgod(a, out c, out d, mode2);
        Console.WriteLine("a = {0}.....b = {1}..... c = {2}.... d = {3}", a, b, c, d);
        outofgod(a, out c, out d, mode3);
        Console.WriteLine("a = {0}.....b = {1}..... c = {2}.... d = {3}", a, b, c, d);
    }
}

}


**

我的班级是班级1的一部分。所以我想使用一个of实例"myclass"。但是当我键入myclass时,什么也没有显示。

您的方法是静态的。不能从静态方法访问非静态字段。

static void YourMethod(....) // notice static keyword
{
}

为了解决这个问题,您可以使myclass成为静态字段。

static Class1 myclass = new Class1();

您可能可以像这样使用

public static class Class1
{
    public static int a;
    public static int b;
    public static int c;
}

然后你可以访问像这样的变量

Class1.a

因为如果你通常尝试这样做,这将是

非静态字段、方法或属性"myclass"

myClass是一个"实例变量",因为Program类不是静态的。此外,由于您的方法是静态的,您不能访问实例变量,因此您应该这样做:

public class Program
{
  Class1 myClass = new Class1();
  public Class1 MyClass{get{return myClass;}}
}
static void godmode()
{
  Program p = new Program();
  var myClass = p.MyClass;
}

但它很糟糕。因此,如果你想使用Class1,你必须在静态方法中实例化它。

最新更新