【发布时间】:2014-10-21 00:53:19
【问题描述】:
谁能告诉我如何在 C# 中的另一个类中实例化和对象。
这里的前 3 个字符串变量(secureID、EmailAddress 和 PhoneNum)我想将它们放在另一个类中,并在这个类中为它们赋值。在 c++ 中,我们会使用朋友类,在 C# 中找不到类似的东西。
进一步说明:
我想用这个代码:
static string SecureId;
static string EmailAddress;
static string PhoneNum;
并将它放在它自己的类中。让我们称之为公共类 myMsg。我想在下面的类 Program 中实例化 myMsg,并能够为其字段分配值,例如 myMsg.SecureId = strDataParse[0]。我在通过类 Program 访问 myMsg 字段时遇到问题。希望对您有所帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace EmailSMSSocketApp
{
class Program
{
static string SecureId;
static string EmailAddress;
static string PhoneNum;
static byte[] Buffer { get; set; }
static Socket _socket;
static void Main(string[] args)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(IPAddress.Any, 1234));
_socket.Listen(100);
Socket accepted = _socket.Accept();
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}
string strData = Encoding.ASCII.GetString(formatted);
//Console.Write(strData + " ASCII to strData" + "\r\n");
string[] strDataParse = strData.Split(',');
foreach (string word in strDataParse)
{
// Console.WriteLine(word);
SecureId = strDataParse[0];
EmailAddress = strDataParse[1];
PhoneNum = strDataParse[2];
};
Console.WriteLine(SecureId + " Outside loop");
Console.WriteLine(EmailAddress + " Outside loop");
Console.WriteLine(PhoneNum + " Outside loop");
Console.Read();
_socket.Close();
accepted.Close();
}
}
}
【问题讨论】:
-
将它们传递给构造函数。我只看到一门课;您能否将代码缩小到与您的问题相关的代码?
-
你提到的变量是静态的。它们是类变量,因此您无需创建 Program 类的实例。您应该能够使用类似 Program.SecureId 的方式访问它们,但您需要定义 getter 和 setter。
-
我试图进一步澄清这一点。让我知道这是否有帮助。