我需要 C# 中类似 C/C++ 的指针的替代方法,以便我可以存储在构造函数中传递的变量的引用。我希望我的本地指针在每次引用值更改时更改其值。就像一个指针。但我不想在 C# 中使用真正的指针,因为它们不安全。有解决方法吗?
class A
{
public Int32 X = 10;
}
class B
{
public B(Int32 x)
{
Y = x;
}
public Int32 Y { get; set; }
}
static void Main(string[] args)
{
A a = new A();
B b = new B(a.X);
Console.WriteLine(b.Y); // 10
a.X = 11;
Console.WriteLine(b.Y); // 10, but I want it to be 11
}
最佳答案
忘掉指针,开始用 C# 思考,同时用 C# 编码:D
我会做这样的事情:
public interface IXProvider
{
int X {get;}
}
class A : IXProvider
{
public int X {get; set;} = 10;
}
class B
{
public B(IXProvider x)
{
_x = x;
}
private readonly IXProvider _x;
public int Y => _x.X;
}
static void Main(string[] args)
{
A a = new A();
B b = new B(a);
Console.WriteLine(b.Y); // 10
a.X = 11;
Console.WriteLine(b.Y); // 11
}
位图示例:(为简单起见,假设“SomeBitmap”和“AnotherBitmap”是实际位图)
public interface IBitmapProvider
{
Bitmap X {get;}
}
class A : IBitmapProvider
{
public Bitmap X {get; set;} = SomeBitmap;
}
class B
{
public B(IBitmapProvider x)
{
_x = x;
}
private readonly IBitmapProvider _x;
public Bitmap Y => _x.X;
}
static void Main(string[] args)
{
A a = new A();
B b = new B(a);
Console.WriteLine(b.Y); // SomeBitmap
a.X = AnotherBitmap;
Console.WriteLine(b.Y); // AnotherBitmap
}
关于c# - C#中的指针替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63593336/