无法使用实例引用来访问成员...;请改用类型名来限定它

前言:开始了牛腩新闻发布系统的简单学习后,按照视频开始一步步地敲代码,果不其然又遇到了错误:

自己的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;

namespace Web
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(new SQLHelper().test());
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public class SQLHelper
    {
        public static int test()
        {
            string connStr = "server=RBY;database=newssystem;uid=sa;pwd=123456";
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();    //打开连接
            string sql = "insert into category(name) values ('测试新闻')";
            SqlCommand cmd = new SqlCommand(sql, conn);
            int res = cmd.ExecuteNonQuery();
            conn.Close();   //关闭连接
            return res;
        }
    }
}

自己去网上查了一下错误,发现了自己代码的问题所在:test()为静态方法,而在Web层的代码我在将SQL Helper实例化后调用了此法。

 

静态方法与非静态方法的区别:

1.静态方法属于类所有,类实例化前就可以使用;

2.非静态方法可以访问类中任何成员,静态方法只能访问类中的静态成员;

3.静态方法在类实例化前就可以使用,而类中的非静态变量必须在实例化后才能分配内存;

4.static内部只能出现static变量和其他static方法,而且static方法不能使用this关键字,因为它属于整个类......

(查询结果引用于:https://zhidao.baidu.com/question/1433773942389340379.html)

 

结合上面的查询结果可以看出,静态方法所在的使用范围是整个类,并且不需要实例化所在类就可以使用。因此在自己Web层的代码中,不需要在Response.Write方法中实例SQLHelper类就可以调用test()方法。

 

 

 

  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值