简体   繁体   English

将对对象属性的引用存储在变量中

[英]Store a reference to a property of an object in a variable

In C# is there any way accomplish something like the following: 在C#中,可以通过任何方式完成以下操作:

class A
{
    public int X { get; set; }
}

class B
{
    public /* ? */ OtherX;
}

var a = new A();
var b = new B();
b.OtherX = //?a.X?;
b.OtherX = 1; //sets a.X to 1
int otherX = b.OtherX //gets value of a.X

without resorting to doing this: 无需采取此操作:

class B
{
    public Func<int> GetOtherX;
    public Action<int> SetOtherX;
}

var a = new A();
var b = new B();
b.GetOtherX = () => a.X;
b.SetOtherX = (x) => a.X = x;

?

No, you can't do this exactly the way you described, since there is no ref int type, but you can put a wrapper around it so you can have both variables point to the same object that holds your value. 不,由于没有ref int类型,因此无法完全按照您描述的方式进行操作,但是可以在其周围放置包装器,以便使两个变量都指向保存您的值的同一对象。

public class Wrapper<T>
{
   public T Value {get; set;}
}

public class A
{
   public Wrapper<int> X {get; set;}

   public A()
   {
       X = new Wrapper<int>();
   }
}

public class B
{
   public Wrapper<int> OtherX {get; set;}
}

var a = new A();
var b = new B();
b.OtherX = a.X;
b.OtherX.Value = 1; //sets a.X to 1
int otherX = b.OtherX.Value //gets value of a.X

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM