在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
没有采取这样做:
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;
答案 0 :(得分:1)
不,你不能按照你描述的方式完全这样做,因为没有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