使变量指向另一个变量

问题描述 投票:1回答:3

我需要一个实例,它是另一个实例的指针。基本上,我将从同一个类创建两个名为A和B的实例。每当我更改A实例的属性时,B实例属性都将被更改。基本上,属性在内存中具有相同的地址。

我只想用不同的变量名来到达同一个对象。每当编辑其中一个时,另一个也应该被编辑。

我怎样才能在Unity中用c#做到这一点?

c# pointers unity3d
3个回答
3
投票

我将有2个相同类型的实例。每当编辑其中一个时,另一个也应该被编辑。

我只想用不同的变量名来到达同一个对象。

您可以使用属性伪造指向另一个变量。这可以通过getset访问器轻松完成。

假设主要变量名为score:

public int score;

您可以使用其他两个变量指向score变量:

public int scoreWithDifferentName1
{
    get { return score; }
    set { score = value; }
}

public int scoreWithDifferentName2
{
    get { return score; }
    set { score = value; }
}

现在,您可以更改分数变量或使用上述两个属性变量访问它:

scoreWithDifferentName1 = 0;
Debug.Log(scoreWithDifferentName1);

要么

scoreWithDifferentName2 = 3;
Debug.Log(scoreWithDifferentName2);

另一种选择是使用IntPtr,但这不是必需的。 C#属性功能足以满足您的需求。这适用于值和引用类型。


2
投票

这似乎是一个设计问题,关于你希望你的课程看起来如何以及他们的职责是什么。我不确定你所说的课程的目的是什么,但这里显而易见的解决方案是带有static修饰符的属性。在类中添加静态属性将确保它在所有实例中具有相同的值,即:

public class ClassX
{
    public static string staticVar = "This is a static string";
    private string var1;
}

1
投票

听起来你正在描述C#中的常规方式引用类型:

public class MyClass
{
    public string Name {get;set;}
}

void Test()
{
    var a = new MyClass();
    a.Name = "Test";
    var b = a;

    Console.WriteLine(a.Name); // "Test"
    Console.WriteLine(b.Name); // "Test"

    b.Name = "MossTeMuerA";
    Console.WriteLine(a.Name); // "MossTeMuerA"
    Console.WriteLine(b.Name); // "MossTeMuerA"

    Mutate(a);
    Console.WriteLine(a.Name); // "John"
    Console.WriteLine(b.Name); // "John"
}

void Mutate(MyClass myClass)
{
    myClass.Name = "John";
}

Example 1

请注意,如果要修改传递给方法的变量指向哪个类实例,则需要使用ref关键字:

void Test()
{
    var a = new MyClass();
    a.Name = "Test";
    var b = a;

    Console.WriteLine(a.Name); // "Test"
    Console.WriteLine(b.Name); // "Test"

    Mutate(ref a);
    Console.WriteLine(a.Name); // "John"
    Console.WriteLine(b.Name); // "Test"
}

void Mutate(ref MyClass myClass)
{
    myClass = new MyClass();
    myClass.Name = "John";
}

Example 2

还有另一个关键字out,它允许方法通过传入要填充的变量来实例化调用者范围内的对象:

void Test()
{
    MyClass a;
    Instantiate(out a);
    Console.WriteLine(a.Name); // "John"
}

void Instantiate(out MyClass myClass)
{
    myClass = new MyClass();
    myClass.Name = "John";
}

Example 3

© www.soinside.com 2019 - 2024. All rights reserved.