【问题标题】:Member cannot be accessed with an instance reference; qualify it with a type name [duplicate]无法使用实例引用访问成员;用类型名称限定它[重复]
【发布时间】:2017-04-03 12:31:40
【问题描述】:

今天我正在研究 c sharp 并且我正在尝试静态类,但它似乎对我不起作用,我很想知道解决方案。 我已经在网上浏览了一段时间,但似乎找不到答案。

这是我的代码:

class Count
{
    public static int sum(int add1, int add2)
    {
        int result = add1 + add2;
        return result;
    }
}

class Program
{
   static void Main(String[] args)
    {
        Console.WriteLine("Adding: \nPlease enter the first number");
        int num1 = int.Parse(Console.ReadLine());
        Console.WriteLine("Please enter the second number");
        int num2 = int.Parse(Console.ReadLine());

        Count add = new Count();
        int total = add.sum(num1, num2);
        Console.WriteLine("The sum is {0}.", total);
        Console.ReadLine();
    }
}

【问题讨论】:

  • 使用Count.sum 而不是实例。
  • 您会看到此错误,因为 sumstatic。遵循 dcg 的搜索结果推荐。

标签: c#


【解决方案1】:

sum 不是实例方法,它必须通过它的类型来访问。替换这个:

Count add = new Count();
int total = add.sum(num1, num2);

有了这个:

int total = Count.sum(num1, num2);

【讨论】:

  • 非常感谢您的回答,这对我有用。
【解决方案2】:

如果您尝试使用静态类 - 将 Count 类标记为静态 - 像这样:

public static class Count

然后在您的代码中使用以下内容:

int total = Count.sum(num1, num2);

它应该按预期工作。

【讨论】:

  • 他确实说static classes,所以他可能确实想要那个。但是Count是否是静态的并不影响他应该如何调用sum
  • @Jonesopolis 正确,如果他正确描述了他试图实现的目标,它只会让他将每个方法都标记为静态 - 但值得注意。
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
相关资源
最近更新 更多