Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在变量中存储对对象属性的引用_C# - Fatal编程技术网

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

C# 在变量中存储对对象属性的引用,c#,C#,在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 {

在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;
B类
{
公共Func GetOtherX;
公共行动SetOtherX;
}
var a=新的a();
var b=新的b();
b、 GetOtherX=()=>a.X;
b、 SetOtherX=(x)=>a.x=x;

不,您不能完全按照您描述的方式执行此操作,因为没有
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
公共类包装器
{
公共T值{get;set;}
}
公共A类
{
公共包装器X{get;set;}
公共A()
{
X=新包装器();
}
}
公共B级
{
公共包装器OtherX{get;set;}
}
var a=新的a();
var b=新的b();
b、 其他X=a.X;
b、 其他x.值=1//将a.X设置为1
int otherX=b.otherX.Value//获取a.X的值

+1。。。我想你可以用
Nullable
代替
Wrapper
。嗯,不幸的是,我不能改变class
A
@mclaassen,我不知道该告诉你什么。。。您需要在int到达B之前将其装箱,以便可以存储引用而不是值。看起来我必须坚持使用
操作
s和
Func
s。好主意。