在我编写的程序中,我有一个包含公共字节数组的类,我想访问和使用它。
class HasByte
{
public byte[] theByteArray = new byte[4];
public HasByte(IPAddress someAddress)
{
theByteArray = someAddress.GetAddressBytes();
}
}
class WantsByte
{
IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance = new HasByte(address);
//do something with theInstance.theByteArray[2] for example
}
目前,我通过theInstance.theByteArray访问的字节数组由于某些我想知道的原因而全部为0。
感谢。
答案 0 :(得分:2)
除了我在评论中所说的封装之外,这里的代码应该对你有用,请注意你在声明它时不能初始化实例,所以你将它移动到构造函数:
public class HasByte
{
public byte[] theByteArray = new byte[4];
public HasByte(IPAddress someAddress)
{
theByteArray = someAddress.GetAddressBytes();
}
}
public class WantsByte
{
IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance;
public WantsByte()
{
theInstance = new HasByte(address);
}
//do something with theInstance.theByteArray[2] for example
}
答案 1 :(得分:1)
在您的班级WantsByte
中,您尝试通过另一个非静态成员theInstance
初始化成员address
,编译器必须向Error CS0236抱怨。您可以将theInstance
初始化移动到构造函数:
class WantsByte
{
IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance;
public WantsByte()
{
theInstance = new HasByte(this.address);
}
}
演示示例:
using System;
using System.Net;
using System.Linq;
public class Program
{
public static void Main()
{
var wants = new WantsByte();
}
}
class HasByte
{
public byte[] theByteArray = new byte[4];
public HasByte(IPAddress someAddress)
{
theByteArray = someAddress.GetAddressBytes();
}
}
class WantsByte
{
IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance;
public WantsByte()
{
theInstance = new HasByte(this.address);
// do something with theInstance.theByteArray[2] for example
// Let's print all elements of the array
Console.WriteLine(String.Join(",", theInstance.theByteArray.Select(o => o.ToString()).ToArray()));
}
}
给出输出:
192,168,1,1
或者,在课程WantsByte
中,您可以将address
设为static
成员,以保证在首次使用课程之前对其进行初始化。然后,您可以在theInstance
初始化程序中引用它:
using System;
using System.Net;
using System.Linq;
public class Program
{
public static void Main()
{
var wants = new WantsByte();
wants.DoSomethingWithHasByte();
}
}
class HasByte
{
public byte[] theByteArray = new byte[4];
public HasByte(IPAddress someAddress)
{
theByteArray = someAddress.GetAddressBytes();
}
}
class WantsByte
{
static IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance = new HasByte(WantsByte.address);
public void DoSomethingWithHasByte()
{
Console.WriteLine(String.Join(",", theInstance.theByteArray.Select(o => o.ToString()).ToArray()));
}
}
也提供相同的输出:
192,168,1,1