如何获得其他类设置的值

时间:2015-03-11 20:34:50

标签: c#

我是C#的新手 我们说我有4个课程:

持有人:

public class Holder
{
    private string name;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
}

二等:

public class SecondClass
{
    public void SecondClassMethod()
    {
        Holder holder = new Holder();
        holder.Name = "John";
        Console.WriteLine(holder.Name + " from SecondClass");
    }
}

AnotherClass:

public class AnotherClass
{
    public void AnotherClassMethod()
    {
        Holder holder = new Holder();
        holder.Name = "Raphael";
        Console.WriteLine(holder.Name + " from AnotherClass");
    }

}

和最终的课程类:

class Program
{
    static void Main(string[] args)
    {
        Holder x1 = new Holder();
        SecondClass x2 = new SecondClass();
        AnotherClass x3 = new AnotherClass();

        x1.Name = "Nobody";
        Console.WriteLine(x1.Name);
        x2.SecondClassMethod();
        Console.WriteLine(x1.Name);
        x3.AnotherClassMethod();
        Console.WriteLine(x1.Name);

        Console.ReadLine();            
    }
}

运行程序后的输出:

Nobody
John from SecondClass
Nobody
Raphael from AnotherClass
Nobody

我的问题是: 我如何使用Program类获得正确的名称(由其他类给出)?事情是我想要使用那套,继续Holder课程。我无法弄清楚。

我想得到:

Nobody
John from SecondClass
John
Raphael from AnotherClass
Raphael

作为输出

2 个答案:

答案 0 :(得分:4)

您在每个班级中实例化new instance Holder。要修改现有实例,您需要pass a reference到其他类。

您可以introducing a constructor执行该操作,您可以在private(最好是readonlyfield中存储对Holder个实例的引用:

public class SecondClass
{
    private readonly Holder _holder;
    public SecondClass(Holder holder)
    {
        _holder = holder;
    }

    public void SecondClassMethod()
    {
        _holder.Name = "John";
        Console.WriteLine(_holder.Name + " from SecondClass");
    }
}

然后使用该类更改代码:

Holder x1 = new Holder();
SecondClass x2 = new SecondClass(x1);

答案 1 :(得分:1)

此外,您可以在类中使用public property来存储要修改的Holder实例的引用:

public class SecondClass
{
    public Holder Holder { get; set; }

    public SecondClass(){}

    public void SecondClassMethod()
    {
        if (Holder!=null)
        {
            Holder.Name = "John";
            Console.WriteLine(Holder.Name + " from SecondClass");
        } 
    }
}

然后在Main方法中你可以这样做:

Holder x1 = new Holder();
SecondClass x2 = new SecondClass(){Holder=x1};
x2.SecondClassMethod();