繁体   English   中英

我如何在 C# 中使用方法?

[英]How can i use methods in c#?

所以,我必须在c#中做一些关于方法的功课。 我对某些点感到困惑。 我写了方法(它们可能是错误的)但我不知道如何调用它们。 这部分怎么写? 例如寻找最大值。 我能写什么? 我尝试了很多次,但无法处理。

此外,此代码必须保存在 txt 文件中,但没有。

    public static void WriteData(StreamWriter sw)
    {
        int[,] a = new int[4, 6];
        Random rnd = new Random();
        for (int i = 0; i < a.GetLength(0); i++)
        {
            for (int J = 0; J < a.GetLength(1); J++)
            {
                a[i, J] = rnd.Next(10, 100);
            }
        }

        Console.WriteLine("\nMATRIX:");
        for (int i = 0; i < a.GetLength(0); i++)
        {
            for (int J = 0; J < a.GetLength(1); J++)
            {
                Console.Write("{0,-4}", a[i, J]);
            }
            Console.WriteLine();
        }

        Console.WriteLine("\nTRANSPOSE:");
        for (int i = 0; i < a.GetLength(1); i++)
        {
            for (int J = 0; J < a.GetLength(0); J++)
            {
                Console.Write("{0,-4}", a[J, i]);
            }
            Console.WriteLine();
        }
    }
    public static void DisplayMatrix(int[,] a) 
    {
        Console.WriteLine("{0}", a);
    }


    public static int MaxNumber(int[] a)
    {
        int max = a[0];

        for (int i = 0; i < a.Length; i++)
        {
            if (max < a[i])
            { max = a[i]; }
        }
        return max;
     }   

    public static void DisplayOddOrEvenForMax(int max)
    {
        if (max % 2 == 0)
        {
            Console.WriteLine("Number is even");

        }
        else
        {
            Console.WriteLine("Number is odd");
        }
    }

    static void Main(string[] args)
    {
        StreamWriter sw = new StreamWriter("MyMatrix.txt", true);
        WriteData(sw);
        sw.Close();
        `

方法(通常)要么附加到类,要么是静态的

如果你有这样的课程:

class MyClass {
    void myMethod() {
       //do something
    }
}

然后你必须创建该类的一个实例,所以是这样的:

MyClass foo = new MyClass() //here foo is the name of the instance

然后在该实例上调用该方法

foo.myMethod()

如果方法是这样静态的:

class MyClass {
    static void myMethod() {
        //do something
    }
}

然后该方法可以通过调用它以及包含它的类直接运行,所以像这样:

MyClass.myMethod()

我希望这有帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM