c# - C#中的指针替代

标签 c# .net pointers

我需要 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/

相关文章:

c# - 将大类从静态转换为非静态的步骤是什么?

c# - RefreshMode.ClientWins 具有多个用户,会发生什么?

c# - 如何基于包含其名称的字符串执行方法

.net - 如何引用附加属性作为数据绑定(bind)的来源?

.net - 检查 .NET 远程服务器是否存在 - 我的方法是否正确?

c# - 防止 MVVM/MDI 应用程序中几乎重复的 RelayCommands

c# - 在 C# WinForm 中计算# of Years Alive

objective-c - 为什么 cStringUsingEncoding : returns const char * instead of char *?

c++ - 来自用作模板参数的指针的类类型

c - 分配给参数指针的空闲内存