回 帖 发 新 帖 刷新版面

主题:大家帮忙看一下这个简单的题错在哪...

以下是我的C#代码[em1]:
using System;
using System.Collections.Generic;
using System.Text;

namespace classof
{
    class Program
    {
        public int max(int a, int b)
        {
            if (a >= b)
            {
                return a;
            }
            else
            {
                return b;
            }
        }
       public static void Main(string[] args)
        {
            int a, b;
            a = Int32.Parse(System.Console.ReadLine());
            b = Int32.Parse(System.Console.ReadLine());
            Console.WriteLine("The max is:{0}", max(a, b));
        }
    }
}
这是我从一个电子书了几科抄下来的,但就是运行不了...[em7]出现这样的错误提示:
对非静态字段,方法或属性"classof.Program.max(int ,int)要求对象引用"...[em6]


我改了一下,但由于学习的时间太短了,不知怎么心...希望各位不吝赐教[em1]

回复列表 (共4个回复)

沙发

public int max(int a, int b)改成:
public static int max(int a, int b)

板凳

使用类名来调用静态方法的,
使用实例来调用实例方法,
这样就可以了,

class Program
    {
        public  static int max(int a, int b)
        {
            if (a >= b)
            {
                return a;
            }
            else
            {
                return b;
            }
        }
        public static void Main(string[] args)
        {
           
            int a, b;
            a = Int32.Parse(System.Console.ReadLine());
            b  = Int32.Parse(System.Console.ReadLine());
            Console.WriteLine("The max is:{0}", Program.max (a,b));
            Console.ReadLine();

3 楼

静态成员类的成员所有,非静态成员类的实例所有

4 楼

谢谢各位的热心帮忙.谢谢....

我来回复

您尚未登录,请登录后再回复。点此登录或注册