文章目录
- 解决方法1:
- 解决方法2:
严重性 代码 说明 项目 文件 行 禁止显示状态
错误 CS0120 对象引用对于非静态的字段、方法或属性“(int)”是必需的 test1 G:\SoftwareLearning\C#resource\chapter05\test1\test1\ 19 活动的
原程序
using System;
using ;
using ;
using System;
namespace Project4
{
class Program
{
public void Method(int x) //形参x是通过值传递的
{
x *= x; // 对x的更改不会影响x的原始值
("Method方法内的值: {0}", x);
}
static void Main()
{
// Program n = new Program();
int y = 9;
("调用Method方法之前的值: {0}", y);
Method(y); // 实参y是通过值传递变量
("调用Method方法后的值: {0}", y);
();
}
}
}
解决方法1:
将Program类实例化后,在调用Method方法
Program n = new Program();
主函数部分程序
Program n = new Program();
int y = 9;
("调用Method方法之前的值: {0}", y);
(y); // 实参y是通过值传递变量
("调用Method方法后的值: {0}", y);
();
解决方法2:
类库中的Method方法设置static
public static void Method(int x)
修改后程序为:
using System;
using ;
using ;
using System;
namespace Project4
{
class Program
{
public static void Method(int x) //形参x是通过值传递的
{
x *= x; // 对x的更改不会影响x的原始值
("Method方法内的值: {0}", x);
}
static void Main()
{
//Program n = new Program();
int y = 9;
("调用Method方法之前的值: {0}", y);
Method(y); // 实参y是通过值传递变量
("调用Method方法后的值: {0}", y);
();
}
}
}