任何Visual Studio程序都不让我编码
本文关键字:编码 Visual Studio 程序 任何 | 更新日期: 2023-09-27 18:35:43
这是最近开始发生的,每次我使用一段代码都算作错误。
例如:
假设我想做一个插座
public class PacketReader
{
Socket MainSocket;
MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); // acts like MainSocket was never declared
// Bind the socket to the selected IP address
MainSocket.Bind(newIPEndPoint(IPAddress.Parse(cmbInterfaces.Text),0));
// Set the socket options
MainSocket.SetSocketOption(SocketOptionLevel.IP, //Applies only to IP packets
SocketOptionName.HeaderIncluded, //Set the include header
true); //option to true
byte[] byTrue = newbyte[4]{1, 0, 0, 0};
byte[] byOut = newbyte[4];
//Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
MainSocket.IOControl(IOControlCode.ReceiveAll, //SIO_RCVALL of Winsock
byTrue, byOut);
//Start receiving the packets asynchronously
MainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
newAsyncCallback(OnReceive), null);
}
然后,当我尝试在函数或类的某些部分中使用它时,它返回为"名称是一个字段,但它用作类型"。我不知道当我所做的只是在类中声明它时,我是如何将其用作类型的。
所以我的问题是,我如何防止这种情况发生。我需要快速找到解决方案,否则由于这个愚蠢的问题,我将在一个月内失败一个项目。
您的代码不在方法中。
不能声明变量并在类范围内单独分配它。您也不能将随机表达式放在类范围内。将您的代码更改为以下内容:
public class PacketReader
{
Socket MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
public PacketReader() {
// rest of the code here in your constructor
}
}
这听起来很卑鄙......但如果你不知道像这样的基本语言结构规则......那么数据包监视器可能只是遥不可及的。
您必须将代码放入一个运行它的方法中!只能在方法范围之外声明变量。需要运行的任何语句都必须位于方法中。不是想粗鲁,但我建议你在尝试这样的事情之前多学一点。有关详细信息,请查看此方法教程。
public class PacketReader
{
Socket MainSocket;
public static void Main()
{
MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); // acts like MainSocket was never declared
// Bind the socket to the selected IP address
MainSocket.Bind(newIPEndPoint(IPAddress.Parse(cmbInterfaces.Text),0));
// Set the socket options
MainSocket.SetSocketOption(SocketOptionLevel.IP, //Applies only to IP packets
SocketOptionName.HeaderIncluded, //Set the include header
true); //option to true
byte[] byTrue = newbyte[4]{1, 0, 0, 0};
byte[] byOut = newbyte[4];
//Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
MainSocket.IOControl(IOControlCode.ReceiveAll, //SIO_RCVALL of Winsock
byTrue, byOut);
//Start receiving the packets asynchronously
MainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
newAsyncCallback(OnReceive), null);
}
}
如果你正在做这样的事情:
Public class YourClass
{
Socket MainSocket;
MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
//other members and methods and so on...
}
例如,这样做...
Public class YourClass
{
Socket MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
//other members and methods and so on...
}
然后,如果您想要其余的,您可以(取决于您的设计和目标)将其放置在构造函数或方法中......