C# 代码错误,未将对象引用设置到对象的实例

private void btnSend_Click(object sender, EventArgs e)
{
if (cbTimeSend.Checked)
{
tmSend.Enabled = true;
}
else
{
tmSend.Enabled = false;
}

        if (!sp1.IsOpen) //如果没打开
        {
            MessageBox.Show("请先打开串口!", "Error");
            return;
        }
       // string strSend = null;
        String strSend = txtSend.Text.ToString();

            if (radio1.Checked == true) //“HEX发送” 按钮 
            {
                //处理数字转换
                string sendBuf = strSend;
                string sendnoNull = sendBuf.Trim();
                string sendNOComma = sendnoNull.Replace(',', ' ');    //去掉英文逗号
                string sendNOComma1 = sendNOComma.Replace(',', ' '); //去掉中文逗号
                string strSendNoComma2 = sendNOComma1.Replace("0x", "");   //去掉0x
                strSendNoComma2.Replace("0X", "");   //去掉0X
                string[] strArray = strSendNoComma2.Split(' ');

                int byteBufferLength = strArray.Length;
                for (int i = 0; i < strArray.Length; i++)
                {
                    if (strArray[i] == "")
                    {
                        byteBufferLength--;
                    }
                }
                // int temp = 0;
                byte[] byteBuffer = new byte[byteBufferLength];
                int ii = 0;
                for (int i = 0; i < strArray.Length; i++)        //对获取的字符做相加运算
                {

                    Byte[] bytesOfStr = Encoding.Default.GetBytes(strArray[i]);

                    int decNum = 0;
                    if (strArray[i] == "")
                    {
                        //ii--;     //加上此句是错误的,下面的continue以延缓了一个ii,不与i同步
                        continue;
                    }
                    else
                    {
                        decNum = Convert.ToInt32(strArray[i], 16); //atrArray[i] == 12时,temp == 18 
                    }

                    try    //防止输错,使其只能输入一个字节的字符
                    {
                        byteBuffer[ii] = Convert.ToByte(decNum);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("字节越界,请逐个字节输入!", "Error");
                        tmSend.Enabled = false;
                        return;
                    }

                    ii++;
                }
                sp1.Write(byteBuffer, 0, byteBuffer.Length);
            }
            else        //以字符串形式发送时 
            {
                sp1.WriteLine(txtSend.Text);    //写入数据
            }

    }

void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//输出当前时间
DateTime dt = DateTime.Now;
txtReceive.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
txtReceive.SelectAll();
txtReceive.SelectionColor = Color.Blue; //改变字体的颜色
try
{
byte[] receivedData = new byte[sp1.BytesToRead]; //创建接收字节数组
sp1.Read(receivedData, 0, receivedData.Length); //读取数据
if (receivedData.Length == 0)
return;
sp1.DiscardInBuffer(); //清空SerialPort控件的Buffer
if (receivedData.Length == 3 && receivedData[0] == 0xFF && receivedData[1] == _totalBytes[1] &&
receivedData[2] == 0x00)

            {
                //_totalBytes[1] = Convert.ToByte(_totalBytes[1] == 0xB5 ? 0xB6 : 0xB5);
                _totalBytes[1] = Convert.ToByte(_totalBytes[1] == 0xB6 ? 0xB5 : 0xB6);
                //_size += _totalBytes[1] == 0xB5 ? 512 : 0;
                _size += _totalBytes[1] == 0xB6 ? 512 : 0;
                SendBytes(false);
            }
            else
            {
                //发送失败
            }
            string strRcv = null;
            if (rdSendStr.Checked)
            {
                strRcv = sp1.Encoding.GetString(receivedData);
            }
            else
            {
                //int decNum = 0;//存储十进制
                for (int i = 0; i < receivedData.Length; i++) //窗体显示
                {

                    strRcv += receivedData[i].ToString("X2");  //16进制显示
                }
            }
            txtReceive.Text += strRcv + "\r\n";
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message, "出错提示");
            txtSend.Text = "";
        }
    }
 串口发送一段指定的字符串,串口接收,串口收到回复消息,提示出错。未将对象引用设置到对象的实例

图片说明





c#

17个回答

判断条件改为:
if(treeView1.SelectedNode==null || treeView1.SelectedNode.Tag ==null)
{

//……
}
原因:
SelectedNode 有可能为空值

SelectedNode 有可能为空值

检查一下配置串口或者SelectedNode 有可能为空值

判断条件改为:
if(treeView1.SelectedNode==null || treeView1.SelectedNode.Tag ==null)
{

//……
}
原因:
SelectedNode 有可能为空值

SelectedNode 有可能为空值
加断点慢慢调试看看哪里有问题

打个断点一步步的调试,直到报错的哪一行,想想为什么为空

判断条件改为:
if(treeView1.SelectedNode==null || treeView1.SelectedNode.Tag ==null)
{

//……
}
原因:
SelectedNode 有可能为空值

共17条数据 首页 2
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于C#“未将对象引用设置到对象的实例”的几个问题。
我是一个超级小白,也是第一次提问,还望各位大佬指教。 首先,我编写了一个WPF窗体和一个TextBox.ID为"aa1"的“TextChanged", 想达到如下目的: 当“aa1”的text值发生改变后,立即实时的将"aa1"的text值赋给TextBox.ID为“aa2”的text。 但是调试时在“aa2.Text = Convert.ToString(x1);”这句话提示“System.NullReferenceException:“未将对象引用设置到对象的实例。” 个人想法是这样的:因为这是“aa1”的TextChanged,所以C#可以知道“aa1”是什么,但是对“aa2”没有说明,导致C#不知道这个“aa2”是什么,问题可能是出在“实例化”与“引用”之间。 想请问各位大佬: 1.对于这种情况我应该怎样去修改? 2.在“未将对象引用设置到对象的实例”这句话中,“对象”指的是什么? 代码片段如下: ``` private void Aa1_TextChanged(object sender, TextChangedEventArgs e) { double x1 = Convert.ToDouble(aa1.Text); aa2.Text = Convert.ToString(x1); } ``` 谢谢。
c#调用webservice 服务器无法处理请求。 ---> 未将对象引用设置到对象的实例
“/”应用程序中的服务器错误。 服务器无法处理请求。 ---> 未将对象引用设置到对象的实例。 说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.ServiceModel.FaultException: 服务器无法处理请求。 ---> 未将对象引用设置到对象的实例。 源错误: 行 128: 行 129: public string[] getWeather(string theCityCode, string theUserID) { 行 130: return base.Channel.getWeather(theCityCode, theUserID); 行 131: } 行 132: 源文件: c:\Users\Administrator\Desktop\WebApplication2\Service References\WeatherWS\Reference.cs 行: 130 堆栈跟踪: [FaultException: 服务器无法处理请求。 ---> 未将对象引用设置到对象的实例。] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10733331 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336 WebApplication2.WeatherWS.WeatherWSSoap.getWeather(String theCityCode, String theUserID) +0 WebApplication2.WeatherWS.WeatherWSSoapClient.getWeather(String theCityCode, String theUserID) in c:\Users\Administrator\Desktop\WebApplication2\Service References\WeatherWS\Reference.cs:130 WebApplication2.WebForm1.test() in c:\Users\Administrator\Desktop\WebApplication2\WebForm1.aspx.cs:19 WebApplication2.WebForm1.Page_Load(Object sender, EventArgs e) in c:\Users\Administrator\Desktop\WebApplication2\WebForm1.aspx.cs:34 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51 System.Web.UI.Control.OnLoad(EventArgs e) +92 System.Web.UI.Control.LoadRecursive() +54 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772 namespace WebApplication2 { public partial class WebForm1 : System.Web.UI.Page { protected void test() { WeatherWS.WeatherWSSoapClient w = new WeatherWS.WeatherWSSoapClient("WeatherWSSoap"); string[] infos = new string[50]; if(w.getWeather("天津","")!=null) infos = w.getWeather("天津", " "); } protected void Page_Load(object sender, EventArgs e) { test(); }
C# 代码明明有获取到数据,为什么还会出现错误“未将对象引用设置到实例”
public TheCustomCheckDetailObj GetTheCustomCheckDetail(int TheCustomCheck) { using (SqlConnection con = new SqlConnection(_connectionString)) { con.Open(); SqlCommand cmd = new SqlCommand("OGetTheCustomCheckDetail", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@TheCustomCheck", SqlDbType.Int); cmd.Parameters["@TheCustomCheck"].Value = TheCustomCheck; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { obj.CurrentCustomDetailObj.CompanyName = Convert.ToString(reader["CompanyName"]); obj.CurrentCustomDetailObj.CompanyPart = Convert.ToString(reader["CompanyPart"]); obj.CurrentCustomDetailObj.CompanyWebsite = Convert.ToString(reader["CompanyWebsite"]); obj.CurrentCustomDetailObj.CustomName = Convert.ToString(reader["CustomName"]); obj.CurrentCustomDetailObj.CustomCellphone = Convert.ToString(reader["CustomCellphone"]); obj.CurrentCustomDetailObj.CustomPhone = Convert.ToString(reader["CustomPhone"]); obj.CurrentCustomDetailObj.CustomFenji = Convert.ToString(reader["CustomFenji"]); obj.CurrentCustomDetailObj.QQorMSN = Convert.ToString(reader["QQorMSN"]); obj.CurrentCustomDetailObj.Email = Convert.ToString(reader["Email"]); obj.CurrentCustomDetailObj.BusinessID = Convert.ToInt32(reader["BusinessID"]); obj.CurrentCustomDetailObj.ProvinceID = Convert.ToInt32(reader["ProvinceID"]); obj.CurrentCustomDetailObj.CountryID = Convert.ToInt32(reader["CountryID"]); obj.CurrentCustomDetailObj.CityID = Convert.ToInt32(reader["CityID"]); obj.CurrentCustomDetailObj.Address = Convert.ToString(reader["Address"]); obj.CurrentCustomDetailObj.PS = Convert.ToString(reader["PS"]); obj.InCheckCustomDetailObj.CompanyName = Convert.ToString(reader["OldCompanyName"]); obj.InCheckCustomDetailObj.CompanyPart = Convert.ToString(reader["OldCompanyPart"]); obj.InCheckCustomDetailObj.CompanyWebsite = Convert.ToString(reader["OldCompanyWebsite"]); obj.InCheckCustomDetailObj.CustomName = Convert.ToString(reader["OldCustomName"]); obj.InCheckCustomDetailObj.CustomCellphone = Convert.ToString(reader["OldCustomCellphone"]); obj.InCheckCustomDetailObj.CustomPhone = Convert.ToString(reader["OldCustomPhone"]); obj.InCheckCustomDetailObj.CustomFenji = Convert.ToString(reader["OldCustomFenji"]); obj.InCheckCustomDetailObj.QQorMSN = Convert.ToString(reader["OldQQorMSN"]); obj.InCheckCustomDetailObj.Email = Convert.ToString(reader["OldEmail"]); obj.InCheckCustomDetailObj.BusinessID = Convert.ToInt32(reader["OldBusinessID"]); obj.InCheckCustomDetailObj.ProvinceID = Convert.ToInt32(reader["OldProvinceID"]); obj.InCheckCustomDetailObj.CountryID = Convert.ToInt32(reader["OldCountryID"]); obj.InCheckCustomDetailObj.CityID = Convert.ToInt32(reader["OldCityID"]); obj.InCheckCustomDetailObj.Address = Convert.ToString(reader["OldAddress"]); obj.InCheckCustomDetailObj.PS = Convert.ToString(reader["OldPS"]); } reader.Close(); con.Close(); return obj; } }
未将对象引用设置到对象的实例。
未将对象引用设置到对象的实例。 说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。 源错误: 行 20: string userName = StrHelper.ConvertSql(UserName.Text.ToString()); 行 21: string userPwd = StrHelper.EncryptPassword(PassWord.Text.ToString(), StrHelper.PasswordType.MD5); 行 22: if (bs.isLoginValidate(userName, userPwd)) 行 23: { 行 24: 源文件: d:\wgm\vs\text\web\Login.aspx.cs 行: 22 堆栈跟踪: [NullReferenceException: 未将对象引用设置到对象的实例。] Leyp.SQLServerDAL.UserDAL.isExistsUserName(String UserName) in C:\Users\yuqin\Desktop\Leyipai\SQLServerDAL\UserDAL.cs:181 Leyp.SQLServerDAL.UserDAL.isLoginValidate(String UserName, String PassWord) in C:\Users\yuqin\Desktop\Leyipai\SQLServerDAL\UserDAL.cs:207 Login.LoginButton_Click(Object sender, ImageClickEventArgs e) in d:\wgm\vs\text\web\Login.aspx.cs:22 System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +115 System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +120 System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563 #**_在这里分享一下我这问题的原因:是因为我的数据库表不全。希望能帮到后来人。_**#
System.NullReferenceException: 未将对象引用设置到对象的实例
在学习微软认知服务,用C#编写了一个简单的接口,但是出现了“未将对象引用设置到对象的实例 (System.NullReferenceException)”这个问题。在网上查了原因,好像有以下几种说法: “System.NullReferenceException: 未将对象引用设置到对象的实例”问题可能原因如下: 1、ViewState 对象为Null。 2、DateSet 空。 3、sql语句或Datebase的原因导致DataReader空。 4、声明字符串变量时未赋空值就应用变量。 5、未用new初始化对象。 6、Session对象为空。 7、对控件赋文本值时,值不存在。 8、使用Request.QueryString()时,所获取的对象不存在,或在值为空时未赋初始值。 9、使用FindControl时,控件不存在却没有做预处理。 10、重复定义造成未将对象引用设置到对象的实例错误. 第一次接触C#,看不出来究竟属于哪一类错误,求问各位大神这个错误应该怎么修正。编译器提示的错误在代码中注释出来了 以下附小弟源码: ``` using System.Collections.Generic; using System.Net.Http; using System.Text; using Newtonsoft.Json; using System; using System.Net.Http.Headers; using System.Web; public class Program { private const string ApiKey = "804e4631f32a421b8cf8066ca2d54fb0"; private const string DescribeImageApiUrl = "https://api.projectoxford.ai/vision/v1.0/describe?maxCandidates=3"; private const string ContentType = "application/json"; public static void Main(string[] args) { var imageUrls = new[] { "http://i.imgur.com/OJ6lzhz.jpg", "http://i.imgur.com/OV80Pr8.jpg" }; foreach(var imageUrl in imageUrls) { var response = DescribeImage(imageUrl); Console.WriteLine("Image: {http://img.taopic.com/uploads/allimg/110910/2316-110910124R147.jpg}"); Console.WriteLine("Descriptions:"); foreach (var caption in response.Description.Captions)//提示错误出现在这一行 { Console.WriteLine(caption.Text); } Console.WriteLine(new string('-', 5)); } Console.Read(); } private static DescribeImageResponse DescribeImage(string imageUrl) { var client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ApiKey); var imageJson = new { url = imageUrl }; var response = client.PostAsync( DescribeImageApiUrl, new StringContent( JsonConvert.SerializeObject(imageJson), Encoding.UTF8, ContentType)).Result; var content = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<DescribeImageResponse>(content); } private class DescribeImageResponse { public DescribeImageResponseDescription Description { get; set; } public string RequestId { get; set; } public DescribeImageResponseMetadata Metadata { get; set; } } private class DescribeImageResponseDescription { public List<string> Tags { get; set; } public List<DescribeImageResponseDescriptionCaption> Captions { get; set; } } private class DescribeImageResponseDescriptionCaption { public string Text { get; set; } public decimal Confidence { get; set; } } private class DescribeImageResponseMetadata { public double Width { get; set; } public double Height { get; set; } public string Format { get; set; } } } ```
报错:System.NullReferenceException: 未将对象引用设置到对象的实例。
本人小白,想实现将网页的表写入到word中并导出到本地。但是总是报错“System.NullReferenceException: 未将对象引用设置到对象的实例。 代码部分如下 ```c# protected void docWriteIn2(string TemplatePath) { Aspose.Words.Document Doc = new Aspose.Words.Document(TemplatePath); //载入模板 DocumentBuilder builder = new DocumentBuilder(Doc); NodeCollection tables = Doc.GetChildNodes(NodeType.Table, true); Aspose.Words.Tables.Table table1 = tables[0] as Aspose.Words.Tables.Table; builder.MoveToBookmark("QInspectionDepartId"); builder.Write(QInspectionDepartId.Text.Trim()); builder.MoveToBookmark("Number"); builder.Write(Number.Text.Trim()); builder.MoveToBookmark("QQuantity"); builder.Write(QQuantity.Text.Trim()); builder.MoveToBookmark("QualifiedQuantity"); builder.Write(QualifiedQuantity.Text.Trim()); builder.MoveToBookmark("UqualifiedQuantity"); builder.Write(UqualifiedQuantity.Text.Trim()); builder.MoveToBookmark("PassRate"); builder.Write(PassRate.Text.Trim()); //拿到第一个表格:tableindex=0 Aspose.Words.Tables.Table table2 = tables[1] as Aspose.Words.Tables.Table; //拿到第二行的row模板:rowindex=1 var roww = table2.Rows[1]; if (Session["receiptNumber"]!=null) { var TestInfo = Testinfo.findTestInfo(Session["receiptNumber"].ToString()); ** QInspectionDepartId.Text = contextdb.S_Department_Info.Single(u => u.id == TestInfo.InspectionDepartId).DepartmentName; ** **//**这里肯定是有问题的**,问题出现在上面这一行**** // 第二行QInspectionDepartId.Text = contextdb.S_Department_Info.Single(u => u.id == DepartId).DepartmentName; } var TestBasicInfoList = db.GetTable<K_QCM_TestBasicInfo>(); var TargetListInfoList = db.GetTable<K_QCM_Target_List>(); var node_table = db.GetTable<K_QCM_Score_Tree>(); var TestBasic = from t in TestBasicInfoList where t.SourceNumber == Session["receiptNumber"].ToString() select t; var list = edit2.findReceiptGiven(Session["receiptNumber"].ToString()); var DetailInfoList = db.GetTable<K_W_Receipt_DetailInfo>(); var ReceiptDetail = from t in DetailInfoList where t.ReceiptNumber == Session["receiptNumber"].ToString() select t; int n = 0; foreach (var s in TestBasic) { var TargetDetail = from t in TargetListInfoList where t.ProductNumber == s.InspectionNumber select t; foreach (var i in TargetDetail) { //Button Button1 = new Button(); //Button1.Text = "按钮"; //Button1.ID = i.id.ToString(); //Button1.Click += new System.EventHandler(Button1_Click); int nodeId = db.K_QCM_Score_Tree.Single(u => u.ParentId == 0 && u.SchemaId == i.SchemaId).id; float value = float.Parse(db.K_QCM_Score_Value.Single(u => u.TargetId == i.id && u.NodeId == nodeId).Value.ToString()); K_QCM_Score_Tree selected_node = node_table.Single(h => h.id == nodeId); if (value == 0) { K_P_Product product = edit.findProductFromCoding(i.ProductCode); //复制第2行 var row = roww.Clone(true); //将复制的行插入当前行的上方 table2.Rows.Insert(1 + n, row); //光标移动到:第一个表格的,第1行的第1列的格子里 builder.MoveToCell(1, n + 1, 0, 0); //给序号填充内容 builder.Write((n + 1).ToString()); //给产品名称单元格填充内容 builder.MoveToCell(1, 1 + n, 1, 0); builder.Write(i.ProductName); //给规格型号填充内容 builder.MoveToCell(1, 1 + n, 2, 0); builder.Write(product.Norm); //给单位填充内容 builder.MoveToCell(1, 1 + n, 3, 0); builder.Write(product.Unit); //给数量填充内容 builder.MoveToCell(1, 1 + n, 4, 0); builder.Write("1"); // builder.MoveToCell(1, 1 + n, 5, 0); builder.Write("不合格"); //总计 } else { K_P_Product product = edit.findProductFromCoding(i.ProductCode); //复制第2行 var row = roww.Clone(true); //将复制的行插入当前行的上方 table2.Rows.Insert(1 + n, row); //光标移动到:第一个表格的,第1行的第1列的格子里 builder.MoveToCell(1, n + 1, 0, 0); //给序号填充内容 builder.Write((n + 1).ToString()); //给产品名称单元格填充内容 builder.MoveToCell(1, 1 + n, 1, 0); builder.Write(i.ProductName); //给规格型号填充内容 builder.MoveToCell(1, 1 + n, 2, 0); builder.Write(product.Norm); //给单位填充内容 builder.MoveToCell(1, 1 + n, 3, 0); builder.Write(product.Unit); //给数量填充内容 builder.MoveToCell(1, 1 + n, 4, 0); builder.Write("1"); //检验结果 builder.MoveToCell(1, 1 + n, 5, 0); builder.Write("合格"); } n = n + 1; } } string docName = "word文档"; Doc.Save(docName + ".doc", Aspose.Words.SaveFormat.Doc, SaveType.OpenInWord, Response); } ``` 报错详细如下 未将对象引用设置到对象的实例。 说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。 有人知道怎么解决吗?
C#萌新遇到了“未将对象引用到对象实例”的问题 希望大佬指点一下
选修的数据库课程用C#做一个前端实现数据库的更改和删除,刚开始学照着书敲了一段代码,运行的时候点击更改就会出现以下错误提示,是我的数据库连接有什么问题吗?求教各位大佬 ![图片说明](https://img-ask.csdn.net/upload/201712/04/1512374007_870907.png)
话说在MVC未将对象引用到实例这个一般是什么导致的呢
如题: “/”应用程序中的服务器错误。 未将对象引用设置到对象的实例。 说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。 源错误: ``` 行 2: @{ 行 3: ViewBag.Title = "添加会员卡"; 行 4: var member = (Member)Session["member"]; 行 5: } 行 6: <ol class="breadcrumb"> ```
c#异步通信代码错误问题
public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } //vs的这段代码中 ,bool connect_flag的connect_flag报了一个警告错误,变量connect_flag已赋值,但是其值从未使用过。如何修改? public static MODEL.DataSourceVersionQuery BrowseDataSource_QueryVersionData() { MODEL.DataSourceVersionQuery result = new MODEL.DataSourceVersionQuery(); //获取数据包 string strPacket = BrowseDataSource_PrepareVersionPacket(); //向服务端提交查询版本信息 string str = DAL.socket.GetSocketData(strPacket); //DAL.socket.GetSocketData(strPacket) vs报了一个错误,非静态字段、方法或属性DAL.socket.GetSocketData(string)“要求对象引用。如何修改? 还有这个错误![图片说明](https://img-ask.csdn.net/upload/201509/16/1442412249_893824.png) 另外我想把DAL中的socket.cs的 public byte[] bytesReceived { get; set; }这段移动到Model中而不报错要如何修改? DAL中socket完整代码如下: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> class socket { //Socket public Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public bool SocketConnect() { byte[] bytesReceived = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } /// <summary> /// 异步连接的回调函数 /// </summary> /// <param name="ar"></param> public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public void SocketSend(string strSend) { Socket clientSocket; //发送创建套接字 int length = strSend.Length; Byte[] bytesSent = new byte[length]; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { bytesSent = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 clientSocket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(SendCallback), clientSocket); //异步发送数据 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } public void SendCallback(IAsyncResult ar) //发送的回调函数 { ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); } /// <summary> /// Socket接收数据 /// </summary> /// <returns> /// 收到的数据 /// </returns> public string SocketReceive() { string result = ""; try { MemoryStream stream = new MemoryStream(); Byte[] bytesReceived = new Byte[256]; clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), clientSocket); ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public void ReceiveCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; //获取句柄 int bytesread = client.EndReceive(ar); if (bytesread > 0) { clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), client); string content = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length); } else { ManualResetEvent readDone = new ManualResetEvent(false); //读信号 readDone.Set(); } } /// <summary> /// Socket通信 /// </summary> /// <param name="strSend"> /// 发送的信息 /// </param> /// <returns> /// 包体的内容 /// </returns> public string GetSocketData(string strSend) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceive(); //获取扩展信息的长度 strExtLength = strResult.Substring(16, 12); int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 strDatas = strResult.Substring(ExtLength + 32); //strDatas = decodedString; } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public string SocketReceiveFile(string FileName) { string result = ""; try { MemoryStream streamPacketLength = new MemoryStream(); Byte[] bytesPacketLength = new Byte[16]; clientSocket.Receive(bytesPacketLength, bytesPacketLength.Length, 0); streamPacketLength.Write(bytesPacketLength, 0, bytesPacketLength.Length); result = System.Text.Encoding.Default.GetString(streamPacketLength.ToArray()); int PacketLength = Convert.ToInt32(result); streamPacketLength.Close(); MemoryStream streamExtLength = new MemoryStream(); Byte[] bytesExtLength = new Byte[12]; clientSocket.Receive(bytesExtLength, bytesExtLength.Length, 0); streamExtLength.Write(bytesExtLength, 0, bytesExtLength.Length); result = System.Text.Encoding.Default.GetString(streamExtLength.ToArray()); int ExtLength = Convert.ToInt32(result); streamExtLength.Close(); MemoryStream streamProtocol = new MemoryStream(); Byte[] bytesProtocol = new Byte[4]; clientSocket.Receive(bytesProtocol, bytesProtocol.Length, 0); streamProtocol.Write(bytesProtocol, 0, bytesProtocol.Length); result = System.Text.Encoding.Default.GetString(streamProtocol.ToArray()); string Protocol = result; streamProtocol.Close(); MemoryStream streamExtInfo = new MemoryStream(); Byte[] bytesExtInfo = new Byte[ExtLength]; clientSocket.Receive(bytesExtInfo, bytesExtInfo.Length, 0); streamExtInfo.Write(bytesExtInfo, 0, bytesExtInfo.Length); result = System.Text.Encoding.Default.GetString(streamExtInfo.ToArray()); byte[] Buffer = Convert.FromBase64String(result); string strExtInfo = UTF8Encoding.UTF8.GetString(Buffer); streamExtInfo.Close(); MODEL.FileTrackQuery ExtInfo = new MODEL.FileTrackQuery(); ExtInfo = JsonConvert.DeserializeObject<MODEL.FileTrackQuery>(strExtInfo); if (ExtInfo.code == "00") { FileInfo fi = new FileInfo(FileName); DirectoryInfo di = fi.Directory; if (!di.Exists) { di.Create(); } FileStream streamPacketInfo = new FileStream(FileName, FileMode.Create); if (PacketLength > 0) { Byte[] bytesPacketInfo = new Byte[PacketLength]; int bytes = 0; do { bytes = clientSocket.Receive(bytesPacketInfo, bytesPacketInfo.Length, 0); streamPacketInfo.Write(bytesPacketInfo, 0, bytes); } while (bytes > 0); } streamPacketInfo.Close(); } clientSocket.Close(); string strLogFile = System.AppDomain.CurrentDomain.BaseDirectory + "debug.txt"; StreamWriter sw = new StreamWriter(strLogFile, true); sw.WriteLine("PacketLength : " + PacketLength.ToString()); sw.WriteLine("ExtLength : " + ExtLength.ToString()); sw.WriteLine("strExtInfo : " + strExtInfo); sw.WriteLine("ExtInfo.code : " + ExtInfo.code); sw.WriteLine("\n------------------------------------------------------------------------\n"); sw.Flush(); sw.Close(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public string GetSocketFile(string strSend, string FileName) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceiveFile(FileName); //获取扩展信息的长度 //strExtLength = strResult.Substring(16, 12); //int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 //strDatas = strResult.Substring(ExtLength + 32); } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public byte[] bytesReceived { get; set; } } } MODEL完整代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MODEL { public enum ClientEditionEnum { Enterprise,//企业版 Personal,//个人版 Internal,//内部版 None,//error } /// <summary> /// 授权文件内容 /// </summary> public class AuthorizeFileInfo { public string startTime { get; set; } public string expiryTime { get; set; } public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public AuthorizeFileInfo() { startTime = ""; expiryTime = ""; licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; } } /// <summary> /// 通用返回值 /// </summary> /// public class CommonResult { public string code { get; set; } public string message { get; set; } public CommonResult() { code = ""; message = ""; } } public class EnterpriseConfirmAuthorizeDatas { public string sessionID { get; set; } public EnterpriseConfirmAuthorizeDatas() { sessionID = ""; } } /// <summary> /// 企业版授权校验接口 /// </summary> public class EnterpriseConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public EnterpriseConfirmAuthorizeDatas datas { get; set; } public EnterpriseConfirmAuthorizeResult() { code = ""; message = ""; datas = new EnterpriseConfirmAuthorizeDatas(); } } public class PersonalConfirmAuthorizeDatas { public string sessionID { get; set; } public string licenseInfo { get; set; } public PersonalConfirmAuthorizeDatas() { sessionID = ""; licenseInfo = ""; } } /// <summary> /// 个人版授权校验接口 /// </summary> public class PersonalConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public PersonalConfirmAuthorizeDatas datas { get; set; } public PersonalConfirmAuthorizeResult() { code = ""; message = ""; datas = new PersonalConfirmAuthorizeDatas(); } } /// <summary> /// 鉴权信息,每次调用安全接口时使用 /// </summary> public class LicInfo { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string deviceID { get; set; } public string sessionID { get; set; } public LicInfo() { licenseID = ""; licensePassword = ""; terminalID = ""; deviceID = ""; sessionID = ""; } } /// <summary> /// java引擎的参数 /// </summary> public class JavaEngineArg { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public string deviceID { get; set; } public JavaEngineArg() { licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; deviceID = ""; } } /// <summary> /// 用户登录接口(一),非安全接口 /// </summary> /// public class UserInfoUnSafe { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public UserInfoUnSafe() { userID = ""; userName = ""; departmentName = ""; } } public class UserLoginUnSafe { public string code { get; set; } public string message { get; set; } public UserInfoUnSafe datas { get; set; } public UserLoginUnSafe() { code = ""; message = ""; datas = new UserInfoUnSafe(); } } /// <summary> /// 个人版用户登录接口,非安全接口 /// </summary> /// public class UserInfoForPersonal { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string licenseInfo { get; set; } public UserInfoForPersonal() { userID = ""; userName = ""; departmentName = ""; licenseInfo = ""; } } public class UserLoginForPersonal { public string code { get; set; } public string message { get; set; } public UserInfoForPersonal datas { get; set; } public UserLoginForPersonal() { code = ""; message = ""; datas = new UserInfoForPersonal(); } } /// <summary> /// 用户登录接口(二),安全接口 /// </summary> /// public class UserInfoSafe { public string userSessionID { get; set; } public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string activeTime { get; set; } public UserInfoSafe() { userSessionID = ""; userID = ""; userName = ""; departmentName = ""; activeTime = ""; } } public class UserLoginSafe { public string code { get; set; } public string message { get; set; } public UserInfoSafe datas { get; set; } public UserLoginSafe() { code = ""; message = ""; datas = new UserInfoSafe(); } } /// <summary> /// 更新检查接口 /// </summary> /// public class SingleVersion { public string softID { get; set; } public int version { get; set; } public SingleVersion() { softID = ""; version = new int(); } } public class Versions { public List<SingleVersion> versions { get; set; } public Versions() { versions = new List<SingleVersion>(); } } public class VersionUpdate { public string softID { get; set; } public int version { get; set; } public string url { get; set; } public VersionUpdate() { softID = ""; version = new int(); url = ""; } } public class VersionCheck { public string code { get; set; } public string message { get; set; } public List<VersionUpdate> datas { get; set; } public VersionCheck() { code = ""; message = ""; datas = new List<VersionUpdate>(); } } /// <summary> /// 数据源信息查询接口 /// </summary> /// public class OptInfoQuery { public string createUserID { get; set; } public string createUserName { get; set; } public string createUserTime { get; set; } public OptInfoQuery() { createUserID = ""; createUserName = ""; createUserTime = ""; } } public class Period { public int cycle { get; set; } public int cycleUnit { get; set; } public string timer { get; set; } public Period() { cycle = 1; cycleUnit = 1; timer = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); } } public class StrategyConfig { public int backType { get; set; } public int taskType { get; set; } public Period config { get; set; } public StrategyConfig() { backType = 0; taskType = 1; config = new Period(); } } public class FilterFileSuffix { public string suffix { get; set; } public FilterFileSuffix() { suffix = ""; } } public class Scan { public int scanType { get; set; } public string root { get; set; } public bool scanHideFile { get; set; } public string verifyCompleteName { get; set; } public int verifyCompleteMaxCount { get; set; } public int verifyCompleteTimer { get; set; } public string fileAttrGainer { get; set; } public bool recordCanNotReadFileInfo { get; set; } public bool recordEmptyDirectory { get; set; } public bool recordEmptyFile { get; set; } public List<FilterFileSuffix> filterFileSuffix { get; set; } public Scan() { scanType = 2; root = ""; scanHideFile = false; verifyCompleteName = ""; verifyCompleteMaxCount = 5; verifyCompleteTimer = 10000; fileAttrGainer = "null"; recordCanNotReadFileInfo = false; recordEmptyDirectory = false; recordEmptyFile = false; filterFileSuffix = new List<FilterFileSuffix>(); } } public class DataSourceConfigQuery { public int status { get; set; } public int dataSourceType { get; set; } public string dataSourceID { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigQuery() { status = 0; dataSourceType = 0; dataSourceID = ""; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } public class DataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<DatasQuery> datas { get; set; } public DataSourceInfoQuery() { code = ""; message = ""; datas = new List<DatasQuery>(); } } public class WebSite { public string ExpirationTime { get; set; } public string WebSiteSpace { get; set; } public bool DataBaseEnable { get; set; } public string DataBaseUserName { get; set; } public string DataBasePassword { get; set; } public string DataBaseMark { get; set; } public string WebSiteAdmin { get; set; } public string WebSitePassword { get; set; } public WebSite() { ExpirationTime = ""; WebSiteSpace = ""; DataBaseEnable = false; DataBaseUserName = ""; DataBasePassword = ""; DataBaseMark = ""; WebSiteAdmin = ""; WebSitePassword = ""; } } public class WebSiteDatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public WebSite webSiteConfig { get; set; } public WebSiteDatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); webSiteConfig = new WebSite(); } } public class WebSiteDataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceInfoQuery() { code = ""; message = ""; datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 新增数据源接口 /// </summary> /// public class OptInfoNew { public bool forceFlag { get; set; } public OptInfoNew() { forceFlag = true; } } public class DataSourceConfigNew { public int dataSourceType { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigNew() { dataSourceType = 0; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DataSourceNew { public OptInfoNew optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigNew dataSourceConfig { get; set; } public DataSourceNew() { optInfo = new OptInfoNew(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigNew(); } } /// <summary> /// 修改数据源接口 /// </summary> /// public class DataSourceModify { public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DataSourceModify() { strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } /// <summary> /// 停用/启用数据源接口 /// </summary> /// public class DataSourceStatus { public string dataSourceID { get; set; } public int optType { get; set; } public DataSourceStatus() { dataSourceID = ""; optType = new int(); } } /// <summary> /// 数据源数据,仅用于存放数据 /// </summary> /// public class DataSourceData { public List<DatasQuery> datas { get; set; } public DataSourceData() { datas = new List<DatasQuery>(); } } /// <summary> /// WebSite数据源数据,仅用于存放数据 /// </summary> /// public class WebSiteDataSourceData { public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceData() { datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 文件恢复,版本查询 /// </summary> /// public class DataSourceVersionArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 前置机编号 public string terminalId { get; set; } // 操作用户编号 public string optUserID { get; set; } public DataSourceVersionArg() { secretKey = ""; token = ""; terminalId = ""; optUserID = ""; } } public class FileVersions { public int file_count { get; set; } public long space_size { get; set; } public string task_id { get; set; } public string task_time { get; set; } public int total_count { get; set; } public string version { get; set; } public FileVersions() { file_count = new int(); space_size = new long(); task_id = ""; task_time = ""; total_count = new int(); version = ""; } } public class DataSourceVersion { public Scan datasourceConfig { get; set; } public string datasourceId { get; set; } public string datasourceName { get; set; } public int datasourceStatus { get; set; } public int datasourceType { get; set; } public List<FileVersions> versions { get; set; } public DataSourceVersion() { datasourceConfig = new Scan(); datasourceId = ""; datasourceName = ""; datasourceStatus = new int(); datasourceType = new int(); versions = new List<FileVersions>(); } } /// <summary> /// 查询数据源接口 /// </summary> public class DataSourceVersionQuery { public string code { get; set; } public string message { get; set; } public List<DataSourceVersion> datas { get; set; } public DataSourceVersionQuery() { code = ""; message = ""; datas = new List<DataSourceVersion>(); } } /// <summary> /// 数据源版本信息 /// </summary> public class DataSourceVersionDatas { public List<DataSourceVersion> datas { get; set; } public DataSourceVersionDatas() { datas = new List<DataSourceVersion>(); } } /// <summary> /// 文件恢复,文件信息查询 /// </summary> /// public class QueryFileInfoArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 数据源编号 public string datasourceId { get; set; } // 操作用户编号 public string optUserID { get; set; } // 目录文件编号--如果为根目录使用 DS_ROOT public string fileID { get; set; } // 查询的版本编号 如果是综合分析 这个字段设置为 ALL public string taskID { get; set; } public QueryFileInfoArg() { secretKey = ""; token = ""; datasourceId = ""; optUserID = ""; fileID = ""; taskID = ""; } } public class FileInfoCondition { public string datasourceId { get; set; } public string parentId { get; set; } public string taskID { get; set; } public FileInfoCondition() { datasourceId = ""; parentId = ""; taskID = ""; } } public class FileInfo { // 文件唯一编号 public string file_id { get; set; } // 源相对目录 public string file_src_path { get; set; } // 文件名 public string file_name { get; set; } // 文件后缀 public string file_suffix { get; set; } // 是否为文件 public bool is_file { get; set; } // 上级文件编号 public string parent_id { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件大小 public int size { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 是否可读 public bool can_read { get; set; } public FileInfo() { file_id = ""; file_src_path = ""; file_name = ""; file_suffix = ""; is_file = new bool(); parent_id = ""; is_del = new bool(); is_hide = new bool(); size = new int(); create_time = ""; create_user = ""; lm_time = ""; lm_user = ""; can_read = new bool(); } } public class FileInfoAndCondition { public FileInfoCondition condition { get; set; } public List<FileInfo> fileInfos { get; set; } public FileInfoAndCondition() { condition = new FileInfoCondition(); fileInfos = new List<FileInfo>(); } } /// <summary> /// 查询文件信息接口 /// </summary> public class FileInfoQuery { public string code { get; set; } public string message { get; set; } public FileInfoAndCondition datas { get; set; } public FileInfoQuery() { code = ""; message = ""; datas = new FileInfoAndCondition(); } } /// <summary> /// 文件信息 /// </summary> public class FileInfoData { public List<FileInfo> datas { get; set; } public FileInfoData() { datas = new List<FileInfo>(); } } public class QueryFileTrackArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 文件编号 public string fileID { get; set; } // 操作用户编号 public string optUserID { get; set; } // 查询的版本编号 public string taskID { get; set; } public QueryFileTrackArg() { secretKey = ""; token = ""; fileID = ""; optUserID = ""; taskID = ""; } } public class FileTrack { // 文件操作 public string act_cmd { get; set; } // 是否可读 public bool can_read { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 文件大小 public int size { get; set; } public string taskID { get; set; } public FileTrack() { act_cmd = ""; can_read = new bool(); create_time = ""; create_user = ""; is_del = new bool(); is_hide = new bool(); lm_time = ""; lm_user = ""; size = new int(); taskID = ""; } } public class FileTrackCondition { public string fileID { get; set; } public string taskID { get; set; } public FileTrackCondition() { fileID = ""; taskID = ""; } } /// <summary> /// 查询文件轨迹接口 /// </summary> public class FileTrackQuery { public string code { get; set; } public string message { get; set; } public FileTrackCondition condition { get; set; } public List<FileTrack> datas { get; set; } public FileTrackQuery() { code = ""; message = ""; condition = new FileTrackCondition(); datas = new List<FileTrack>(); } } /// <summary> /// 文件轨迹 /// </summary> public class FileTrackData { public List<FileTrack> datas { get; set; } public FileTrackData() { datas = new List<FileTrack>(); } } /// <summary> /// 字典item /// </summary> public class DictionaryData { public string version { get; set; } public string task_time { get; set; } public DictionaryData() { version = ""; task_time = ""; } } public class FileRecoverArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 操作用户编号 public string optUserID { get; set; } public string fileID { get; set; } public string taskID { get; set; } public string password { get; set; } public FileRecoverArg() { secretKey = ""; token = ""; optUserID = ""; fileID = ""; taskID = ""; password = ""; } } }
用dataAdapter.update更新DataGridView中的数据,代码总是抛出异常说 dataAdapter 是 null,该怎么修改?
用dataAdapter.update更新DataGridView中的数据,代码总是抛出异常System.NullReferenceException:“未将对象引用设置到对象的实例。” dataAdapter 是 null,该怎么修改? 这里是详细代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace 项目二 { public partial class Form1 : Form { SqlDataAdapter dataAdapter; DataSet dataSet; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connString = "Data Source = (local);Initial Catalog = Mybookshop;User ID = sa;pwd = 123456"; SqlConnection con = new SqlConnection(connString); string sql = "SELECT * FROM book1"; SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con); DataSet dataSet; dataSet = new DataSet(); dataAdapter.Fill(dataSet, "Mydata"); dataGridView1.DataSource = dataSet.Tables[0]; } private void button2_Click(object sender, EventArgs e) { SqlCommandBuilder builder = new SqlCommandBuilder(dataAdapter); dataAdapter.Update(dataSet, "Mydata"); } } } ![图片说明](https://img-ask.csdn.net/upload/201912/06/1575634228_121330.png) 输入数据点击更新后错误显示为 ![图片说明](https://img-ask.csdn.net/upload/201912/06/1575634258_789589.png)
C# 多线程读写删除文件并绘制在picture上
namespace PictureSD { public partial class Form1 : Form { public Form1() { InitializeComponent(); } bool flag; bool flag2; private Object thisLock = new object(); ComputePic face; Thread ThreadSamp;// 图片 Bitmap bc1; Bitmap bc2; Graphics gc1; private string dir = @"C:\Users\Teefan\Desktop\C#聊天\NEWFACElog\Camera\Camera\bin\Debug\Images\7.jpg"; private string dir2 = @"C:\Users\Teefan\Desktop\C#聊天\NEWFACElog\Camera\Camera\bin\Debug\Images"; private void button1_Click(object sender, EventArgs e) { System.Drawing.Image img= System.Drawing.Image.FromFile(dir);// 读7号图片测试 Bitmap imgBit = new Bitmap(img); SaveBit(imgBit, dir2, 2, "jpg");//存2号 imgBit.Dispose(); if (face == null) { ThreadSamp = new Thread(createSamp); // 计算人脸 ThreadSamp.IsBackground = true; ThreadSamp.Start(); } ThreadSamp.Join(); bc1.Dispose(); gc1.Dispose(); string img2 = dir2 + "/" + 2.ToString() + ".jpg"; File.Delete(img2); } class ComputePic { public int weight; public int height; public ComputePic(int a,int b) { weight = a; height = b; } } private void createSamp() { flag2 = false; face = new ComputePic(pictureBox1.Width, pictureBox1.Height); //假定在计算 bc1 = new Bitmap(dir2 + "/" + "2.jpg"); gc1 = Graphics.FromImage(bc1); RectangleF rect1 = new RectangleF(10, 20, face.weight++, face.height++); gc1.DrawImage(bc1, 0, 0, rect1, GraphicsUnit.Pixel); pictureBox1.Invoke((MethodInvoker)delegate //操作其他控件的语句 { pictureBox1.Image = bc1; pictureBox1.Refresh(); }); face = null; } private bool SaveBit(Bitmap bitmap, string path, int num, string kind) { string img = path + "/" + num.ToString() + "." + kind; bitmap.Save(img); return flag = true; } private void timer1_Tick(object sender, EventArgs e) { // button1_Click(button1, null); } private void button2_Click(object sender, EventArgs e) { System.Timers.Timer t = new System.Timers.Timer(2000); //实例化Timer类,设置间隔时间为10000毫秒; t.Elapsed += new System.Timers.ElapsedEventHandler(button1_Click); //到达时间的时候执行事件; t.AutoReset = true; //设置是执行一次(false)还是一直执行(true); t.Enabled = true; } } } 是这样的,我做了一个界面想实现一个功能,相当于读7号图片,存时命名为2号,然后利用多线程计算2号图片,得到坐标,在绘制picture上,最后删除2号图片,再读7号,在2号计算、坐标、绘制。基本就是这个顺序不要乱,可是我琢磨几天了,要么gdi错误,要么bc1对象被别处引用,我不知道我这样的顺序应该怎么实现!或许很简单,可是我琢磨好久了,真心求教多线程而且能做到不会冲突的高手,我的代码只能基本实现图片删除,不能体现在picture画的样子刷新上!
c#用serialport进行的串口数据接收,遇到了问题,求大神指点
运行后再richtextbox1中只显示一个数,例如:33 随后会报错:对象未引用到对象的实例,点了关闭后又会出现一个数据,例如31,之后又会报错,如此循环,而且数据不太对。 整了好久了,希望能帮帮忙,第一次做这,谢谢!! 代码: namespace yfy_串口调试 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /****************************设置变量******************************/ public string[] strArray; public SerialPort sp1 = new SerialPort(); public Byte[] mydata; public int mydatalength; //这个数的值是由接收到的字节长度决定的,并且作为mydata的长度,如果索引值还超过数组定义值,就应该是接收问题。 public int zhengfu = 2, now_x = 30; public static Bitmap bmp = new Bitmap(500,350); public Graphics gph = Graphics.FromImage(bmp); public char name_image='A'; /*****************************相关函数****************************/ public void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)//数据接收函数 { if (sp1.IsOpen==true ) //为了严谨性,加上检查串口是否被打开 { if (rbRcv16.Checked == true) //接收16进制按钮 { try { int average_speed = 0; //设置初始平均速度 Byte[] receivedData = new Byte[sp1.BytesToRead]; //创建接收字节数组 sp1.Read(receivedData, 0, receivedData.Length); //读取数据 sp1.DiscardInBuffer(); //清空SerialPort控件的Buffer mydatalength = receivedData.Length; for (int i = 0; i < receivedData.Length; i++) //窗体显示 { richTextBox1.Text = receivedData[i].ToString("X2"); //16进制显示在接受栏 mydata[i] = receivedData[i]; richTextBox1.Text += ","; //让每个数据都隔开 average_speed += receivedData[i]; } textBox1.Text = (average_speed / receivedData.Length).ToString("X2"); } catch (System.Exception ex) { MessageBox.Show(ex.Message, "出错提示"); } } } else { MessageBox.Show("请打开某个串口或者没有选中16进制接收", "错误提示"); } } private void Form1_Load(object sender, EventArgs e)//页面初始化 { Control.CheckForIllegalCrossThreadCalls = false; //强制不检查线程 sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived); //订阅委托 sp1.ReceivedBytesThreshold =1; //当缓冲区的字节数为x时,触发datareceive事件 //检查是否有串口 string[] str = SerialPort.GetPortNames(); if (str == null) { MessageBox.Show("本机没有串口!", "Error!"); return; } //添加串口项目 foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) { cbSerial.Items.Add(s); //获取有COM口 } rbRcv16.Checked = true; //接收数据按16进制进行 } private void btnSwitch_Click(object sender, EventArgs e)//设置串口 { if (sp1.IsOpen == false) { try { string serialName = cbSerial.SelectedItem.ToString();//读取串口号 sp1.PortName = serialName; //设置串口号 sp1.BaudRate = 9600; //波特率 sp1.DataBits = 8; //数据位 sp1.StopBits = StopBits.One; //停止位 sp1.Parity = Parity.None; //校验位 sp1.Open(); //打开串口 btnSwitch.Text = "关闭串口"; } catch (System.Exception ex) { MessageBox.Show("Error:" + ex.Message, "Error"); return; } } else { sp1.Close(); //关闭串口 btnSwitch.Text = "打开串口"; } }
ArcGIS Engine10.0 显示属性表的时候不成功,代码最后两行有问题,已标注,求解。
源码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Geodatabase; namespace GIS_Design { public partial class Form1 : Form { public Form1() { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop); InitializeComponent(); } private void axMapControl1_OnMapReplaced(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMapReplacedEvent e) { if (axMapControl1.LayerCount > 0) { axMapControl2.Map = new MapClass(); for (int i = 0; i <= axMapControl1.Map.LayerCount - 1; i++) { axMapControl2.AddLayer(axMapControl1.get_Layer(i)); } axMapControl2.Extent = axMapControl1.Extent; axMapControl2.Refresh(); } } private void axMapControl1_OnExtentUpdated(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnExtentUpdatedEvent e) { // 得到新范围 IEnvelope pEnvelope = (IEnvelope)e.newEnvelope; IGraphicsContainer pGraphicsContainer = axMapControl2.Map as IGraphicsContainer; IActiveView pActiveView = pGraphicsContainer as IActiveView; //在绘制前,清除axMapControl2中的任何图形元素 pGraphicsContainer.DeleteAllElements(); IRectangleElement pRectangleEle = new RectangleElementClass(); IElement pElement = pRectangleEle as IElement; pElement.Geometry = pEnvelope; //设置鹰眼图中的红线框 IRgbColor pColor = new RgbColorClass(); pColor.Red = 255; pColor.Green = 0; pColor.Blue = 0; pColor.Transparency = 255; //产生一个线符号对象 ILineSymbol pOutline = new SimpleLineSymbolClass(); pOutline.Width = 3; pOutline.Color = pColor; //设置颜色属性 pColor = new RgbColorClass(); pColor.Red = 255; pColor.Green = 0; pColor.Blue = 0; pColor.Transparency = 0; //设置填充符号的属性 IFillSymbol pFillSymbol = new SimpleFillSymbolClass(); pFillSymbol.Color = pColor; pFillSymbol.Outline = pOutline; IFillShapeElement pFillShapeEle = pElement as IFillShapeElement; pFillShapeEle.Symbol = pFillSymbol; pGraphicsContainer.AddElement((IElement)pFillShapeEle, 0); pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } private void axMapControl2_OnMouseMove(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseMoveEvent e) { if (e.button == 1) { IPoint pPoint = new ESRI.ArcGIS.Geometry.Point(); pPoint.PutCoords(e.mapX, e.mapY); axMapControl1.CenterAt(pPoint); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } } private void axMapControl2_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e) { if (axMapControl2.Map.LayerCount > 0) { if (e.button == 1) { IPoint pPoint = new ESRI.ArcGIS.Geometry.Point(); pPoint.PutCoords(e.mapX, e.mapY); axMapControl1.CenterAt(pPoint); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } else if (e.button == 2) { IEnvelope pEnv = axMapControl2.TrackRectangle(); axMapControl1.Extent = pEnv; axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } } } private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e) { } ILayer layer = new FeatureLayerClass(); private void axTOCControl1_OnMouseDown_1(object sender, ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e) { this.axTOCControl1.ContextMenuStrip = null; IBasicMap map = new MapClass(); System.Object other = null; System.Object index = null; ESRI.ArcGIS.Controls.esriTOCControlItem item = ESRI.ArcGIS.Controls.esriTOCControlItem.esriTOCControlItemNone; this.axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref layer, ref other, ref index); if (item == ESRI.ArcGIS.Controls.esriTOCControlItem.esriTOCControlItemLayer && e.button == 2) { System.Drawing.Point pt = new System.Drawing.Point(); pt.X = e.x; pt.Y = e.y; pt = this.axTOCControl1.PointToScreen(pt); this.contextMenuStrip4.Show(pt); } } private void OpenAttribute_Click(object sender, EventArgs e) { **Form Attribute = new Attribute(layer); Form.Show();** } } } 错误 CS0144: 无法创建抽象类或接口“System.Attribute”的实例 错误 CS0120: 非静态的字段、方法或属性“System.Windows.Forms.Control.Show()”要求对象引用
调用外部DLL后无法使用
![图片说明](https://img-ask.csdn.net/upload/201809/19/1537287984_606022.jpg) ![图片说明](https://img-ask.csdn.net/upload/201809/19/1537287996_207977.jpg) ![图片说明](https://img-ask.csdn.net/upload/201809/19/1537288023_380041.jpg) 如图所示,外部DLL引用后可以在对象浏览器中看到接口,但是写代码的时候却无法直接使用也无法实例化, VS的错误代码说明太简洁,搜了一些文章对于我这个情况都没用,所以现在我需要明确的知道我要做什么 如果可以的话,希望能给出对于IFileStream.Open使用示例
main函数创建Configuration() 没有问题,在controller上执行就报错
## 具体错误代码如下 ``` 2018-12-05 17:25:39,486 DEBUG [servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver] - Resolving exception from handler [public java.lang.String com.chinagdn.base.web.ss.SweepCompanyController.uploadReport(com.chinagdn.base.vo.ReportWordVo)]: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration 2018-12-05 17:25:39,486 DEBUG [web.servlet.mvc.annotation.ResponseStatusExceptionResolver] - Resolving exception from handler [public java.lang.String com.chinagdn.base.web.ss.SweepCompanyController.uploadReport(com.chinagdn.base.vo.ReportWordVo)]: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration 2018-12-05 17:25:39,498 DEBUG [web.servlet.mvc.support.DefaultHandlerExceptionResolver] - Resolving exception from handler [public java.lang.String com.chinagdn.base.web.ss.SweepCompanyController.uploadReport(com.chinagdn.base.vo.ReportWordVo)]: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration 2018-12-05 17:25:39,499 DEBUG [springframework.web.servlet.handler.SimpleMappingExceptionResolver] - Resolving exception from handler [public java.lang.String com.chinagdn.base.web.ss.SweepCompanyController.uploadReport(com.chinagdn.base.vo.ReportWordVo)]: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration 2018-12-05 17:25:39,500 DEBUG [springframework.web.servlet.handler.SimpleMappingExceptionResolver] - Resolving to view 'error/500' for exception of type [org.springframework.web.util.NestedServletException], based on exception mapping [java.lang.Throwable] 2018-12-05 17:25:39,500 DEBUG [springframework.web.servlet.handler.SimpleMappingExceptionResolver] - Exposing Exception as model attribute 'exception' 2018-12-05 17:25:39,500 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'error/500'; model is {exception=org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration} org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:982) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61) at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108) at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137) at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66) at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383) at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1152) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:724) Caused by: java.lang.NoClassDefFoundError: freemarker/template/Configuration at com.chinagdn.base.web.ss.SweepCompanyController.uploadReport(SweepCompanyController.java:128) at com.chinagdn.base.web.ss.SweepCompanyController$$FastClassBySpringCGLIB$$9b19d86b.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor$1.proceed(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:82) at org.apache.shiro.authz.aop.AuthorizingMethodInterceptor.invoke(AuthorizingMethodInterceptor.java:39) at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor.invoke(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:115) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) at com.chinagdn.base.web.ss.SweepCompanyController$$EnhancerBySpringCGLIB$$84209520.uploadReport(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ... 47 more 2018-12-05 17:25:39,509 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Rendering view [org.springframework.web.servlet.view.JstlView: name 'error/500'; URL [/WEB-INF/views/error/500.jsp]] in DispatcherServlet with name 'springMvc' 2018-12-05 17:25:39,509 DEBUG [springframework.web.servlet.view.JstlView] - Added model object 'exception' of type [org.springframework.web.util.NestedServletException] to request in view with name 'error/500' 2018-12-05 17:25:39,509 DEBUG [springframework.web.servlet.view.JstlView] - Forwarding to resource [/WEB-INF/views/error/500.jsp] in InternalResourceView 'error/500' 2018-12-05 17:25:39,514 ERROR [500.jsp] - Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: freemarker/template/Configuration at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:982) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61) at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108) at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137) at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66) at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383) at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1152) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:724) Caused by: java.lang.NoClassDefFoundError: freemarker/template/Configuration at com.chinagdn.base.web.ss.SweepCompanyController.uploadReport(SweepCompanyController.java:128) at com.chinagdn.base.web.ss.SweepCompanyController$$FastClassBySpringCGLIB$$9b19d86b.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor$1.proceed(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:82) at org.apache.shiro.authz.aop.AuthorizingMethodInterceptor.invoke(AuthorizingMethodInterceptor.java:39) at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor.invoke(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:115) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) at com.chinagdn.base.web.ss.SweepCompanyController$$EnhancerBySpringCGLIB$$84209520.uploadReport(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ... 47 more 2018-12-05 17:25:39,537 DEBUG [springframework.web.multipart.commons.CommonsMultipartResolver] - Cleaning up multipart file [list[0].file] with original filename [], stored in memory 2018-12-05 17:25:39,537 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request 2018-12-05 17:25:39,575 DEBUG [apache.shiro.web.servlet.SimpleCookie] - Found 'jeesite.session.id' cookie value [8085a300-c84d-470f-a511-132f708a97f9] 2018-12-05 17:25:39,575 DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'springMvc' processing GET request for [/css/common.css] 2018-12-05 17:25:39,575 DEBUG [servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /css/common.css 2018-12-05 17:25:39,595 DEBUG [servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Did not find handler method for [/css/common.css] 2018-12-05 17:25:39,596 DEBUG [springframework.web.servlet.handler.SimpleUrlHandlerMapping] - Matching patterns for request [/css/common.css] are [/css/**] 2018-12-05 17:25:39,597 DEBUG [springframework.web.servlet.handler.SimpleUrlHandlerMapping] - URI Template variables for request [/css/common.css] are {} 2018-12-05 17:25:39,597 DEBUG [springframework.web.servlet.handler.SimpleUrlHandlerMapping] - Mapping [/css/common.css] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/WEB-INF/css/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@4219e435]]] and 1 interceptor 2018-12-05 17:25:39,597 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Last-Modified value for [/css/common.css] is: -1 2018-12-05 17:25:39,600 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'springMvc': assuming HandlerAdapter completed request handling 2018-12-05 17:25:39,600 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request 2018-12-05 17:26:50,014 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Executing session validation... 2018-12-05 17:26:50,014 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Validating all active sessions... 2018-12-05 17:26:50,014 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Finished session validation. No sessions were stopped. 2018-12-05 17:26:50,014 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Session validation completed successfully in 0 milliseconds. 2018-12-05 17:28:50,021 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Executing session validation... 2018-12-05 17:28:50,021 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Validating all active sessions... 2018-12-05 17:28:50,022 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Finished session validation. No sessions were stopped. 2018-12-05 17:28:50,022 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Session validation completed successfully in 1 milliseconds. 2018-12-05 17:30:50,017 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Executing session validation... 2018-12-05 17:30:50,017 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Validating all active sessions... 2018-12-05 17:30:50,017 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Finished session validation. No sessions were stopped. 2018-12-05 17:30:50,017 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Session validation completed successfully in 0 milliseconds. 2018-12-05 17:32:50,015 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Executing session validation... 2018-12-05 17:32:50,015 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Validating all active sessions... 2018-12-05 17:32:50,015 INFO [apache.shiro.session.mgt.AbstractValidatingSessionManager] - Finished session validation. No sessions were stopped. 2018-12-05 17:32:50,015 DEBUG [apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler] - Session validation completed successfully in 0 milliseconds. ``` - maven依赖如下 - ```<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency> ``` - 创建的一个类,在自己的main函数下可以正常运行 ```java package com.chinagdn.base.common.utils; import freemarker.template.Configuration; public class DocumentHandler { private Configuration configuration = null; public DocumentHandler() { // Configuration对象在main函数下创建没有问题, // 在controller创建就会报错 configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); } public static void main(String[] args) { //此处可以创建实例,不会报错 DocumentHandler d = new DocumentHandler(); try { .... } catch (IOException e) { e.printStackTrace(); } } ``` - 如果在 controller 层创建此对象则会报错 ```java @RequiresPermissions("ss:sweep:buploadReport") @RequestMapping(value = "/uploadReport/save", method = RequestMethod.POST) public String uploadReport(ReportWordVo ReportWordVo){ //创建这个对象的时候就会报错,实际是他的构造函数中创建的对象有问题 DocumentHandler documentHandler = new DocumentHandler(); return null; } ``` ## 尝试过的方式 - 百度说是没有引用依赖 (尝试过 2.3.20/2.3.23 版本) - `Configuration`对象在main函数下跑的时候没有问题,在controller下面跑就报错 ## 图片 - ![图片说明](https://img-ask.csdn.net/upload/201812/05/1544003677_775994.jpg) - ![图片说明](https://img-ask.csdn.net/upload/201812/05/1544003923_923694.jpg)
相见恨晚的超实用网站
相见恨晚的超实用网站 持续更新中。。。
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载 点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。 ...
字节跳动视频编解码面经
三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时想着能进去就不错了,管他哪个岗呢,就同意了面试...
开源一个功能完整的SpringBoot项目框架
福利来了,给大家带来一个福利。 最近想了解一下有关Spring Boot的开源项目,看了很多开源的框架,大多是一些demo或者是一个未成形的项目,基本功能都不完整,尤其是用户权限和菜单方面几乎没有完整的。 想到我之前做的框架,里面通用模块有:用户模块,权限模块,菜单模块,功能模块也齐全了,每一个功能都是完整的。 打算把这个框架分享出来,供大家使用和学习。 为什么用框架? 框架可以学习整体...
源码阅读(19):Java中主要的Map结构——HashMap容器(下1)
HashMap容器从字面的理解就是,基于Hash算法构造的Map容器。从数据结构的知识体系来说,HashMap容器是散列表在Java中的具体表达(并非线性表结构)。具体来说就是,利用K-V键值对中键对象的某个属性(默认使用该对象的“内存起始位置”这一属性)作为计算依据进行哈希计算(调用hashCode方法),然后再以计算后的返回值为依据,将当前K-V键值对在符合HashMap容器构造原则的基础上,放置到HashMap容器的某个位置上,且这个位置和之前添加的K-V键值对的存储位置完全独立,不一定构成连续的存储
c++制作的植物大战僵尸,开源,一代二代结合游戏
此游戏全部由本人自己制作完成。游戏大部分的素材来源于原版游戏素材,少部分搜集于网络,以及自己制作。 此游戏为同人游戏而且仅供学习交流使用,任何人未经授权,不得对本游戏进行更改、盗用等,否则后果自负。目前有六种僵尸和六种植物,植物和僵尸的动画都是本人做的。qq:2117610943 开源代码下载 提取码:3vzm 点击下载--&gt; 11月28日 新增四种植物 统一植物画风,全部修...
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
Python——画一棵漂亮的樱花树(不同种樱花+玫瑰+圣诞树喔)
最近翻到一篇知乎,上面有不少用Python(大多是turtle库)绘制的树图,感觉很漂亮,我整理了一下,挑了一些我觉得不错的代码分享给大家(这些我都测试过,确实可以生成) one 樱花树 动态生成樱花 效果图(这个是动态的): 实现代码 import turtle as T import random import time # 画樱花的躯干(60,t) def Tree(branch, ...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
Python 基础(一):入门必备知识
Python 入门必备知识,你都掌握了吗?
深度学习图像算法在内容安全领域的应用
互联网给人们生活带来便利的同时也隐含了大量不良信息,防范互联网平台有害内容传播引起了多方面的高度关注。本次演讲从技术层面分享网易易盾在内容安全领域的算法实践经验,包括深度...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Python 编程实用技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法,并会持续更新。
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
"狗屁不通文章生成器"登顶GitHub热榜,分分钟写出万字形式主义大作
前言 GitHub 被誉为全球最大的同性交友网站,……,陪伴我们已经走过 10+ 年时间,它托管了大量的软件代码,同时也承载了程序员无尽的欢乐。 上周给大家分享了一篇10个让你笑的合不拢嘴的Github项目,而且还拿了7万+个Star哦,有兴趣的朋友,可以看看, 印象最深刻的是 “ 呼吸不止,码字不停 ”: 老实交代,你是不是经常准备写个技术博客,打开word后瞬间灵感便秘,码不出字? 有什么
推荐几款比较实用的工具,网站
1.盘百度PanDownload 这个云盘工具是免费的,可以进行资源搜索,提速(偶尔会抽风????) 不要去某站买付费的???? PanDownload下载地址 2.BeJSON 这是一款拥有各种在线工具的网站,推荐它的主要原因是网站简洁,功能齐全,广告相比其他广告好太多了 bejson网站 3.二维码美化 这个网站的二维码美化很好看,网站界面也很...
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
Spring Security 实战干货:基于注解的接口角色访问控制
1. 前言 欢迎阅读 Spring Security 实战干货[1] 系列文章 。在上一篇 基于配置的接口角色访问控制[2] 我们讲解了如何通过 javaConfig 的方式配置接口的角色访问控制。其实还有一种更加灵活的配置方式 基于注解 。今天我们就来探讨一下。DEMO 获取方式在文末。 2. Spring Security 方法安全 Spring Security 基于注解的安全...
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
相关热词 c# 图片上传 c# gdi 占用内存 c#中遍历字典 c#控制台模拟dos c# 斜率 最小二乘法 c#进程延迟 c# mysql完整项目 c# grid 总行数 c# web浏览器插件 c# xml 生成xsd
立即提问