指向C#中其他类拥有的变量

时间:2019-07-10 14:09:28

标签: c# pointers ref

在下面的代码中,我希望对Main的名称都为“ GoodBye”的东西都以classA和Main结尾。但是,最后,classA仍然将Main的名称为“ Hello”,而Main知道它的名称为已更改为“ GoodBye”。如何允许classA看到Main的名称已更改为GoodBye?

在C#中是否不允许这样做并且被认为是不安全的,因此您必须将代码包装在“不安全”的块中?

经过测试后,我了解到使用引用可以使classA修改Main的名称,但不允许classA查看Main的名称何时被更改。

{ "resourceType": "Bundle",
....}

上面的输出如下:

class Program
{
    static void Main(string[] args)
    {
        string MyName = "Hello";

        Console.WriteLine($"Main thinks Main's name is: {MyName}");
        Console.WriteLine($"");

        Console.WriteLine($"Creating ClassA");
        ClassA classA = new ClassA(ref MyName);

        Console.WriteLine($"Main thinks Main's name is: {MyName}");
        classA.WriteOutMainName();

        MyName = "GoodBye";
        Console.WriteLine($"");
        Console.WriteLine($"Main changed it's name to: {MyName}");
        Console.WriteLine($"");

        Console.WriteLine($"Main thinks Main's name is: {MyName}");
        classA.WriteOutMainName();

    }
}

public class ClassA
{
    string MainName;
    public ClassA(ref string mainName)
    {
        MainName = mainName;
        mainName = "Dog";
    }

    public void WriteOutMainName()
    {
        Console.WriteLine($"ClassA thinks Main's name is: {MainName}");
    }
}

1 个答案:

答案 0 :(得分:0)

在测试了艾米的上述陈述后进行了更新:

以下内容可按需工作:

class Program
{
    static void Main(string[] args)
    {
        //string MyName = "Hello";

        NameHolder MyName = new NameHolder();
        MyName.Name = "hello";

        Console.WriteLine($"Main thinks Main's name is: {MyName.Name}");
        Console.WriteLine($"");

        Console.WriteLine($"Creating ClassA");
        ClassA classA = new ClassA(MyName);

        Console.WriteLine($"Main thinks Main's name is: {MyName.Name}");
        classA.WriteOutMainName();

        MyName.Name = "GoodBye";
        Console.WriteLine($"");
        Console.WriteLine($"Main changed it's name to: {MyName.Name}");
        Console.WriteLine($"");

        Console.WriteLine($"Main thinks Main's name is: {MyName.Name}");
        classA.WriteOutMainName();

    }
}

public class ClassA
{
    NameHolder MainName;
    public ClassA(NameHolder mainName)
    {
        MainName = mainName;
    }

    public void WriteOutMainName()
    {
        Console.WriteLine($"ClassA thinks Main's name is: {MainName.Name}");
    }
}

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

输出如下:

Main thinks Main's name is: hello

Creating ClassA

Main thinks Main's name is: hello
ClassA thinks Main's name is: hello

Main changed it's name to: GoodBye

Main thinks Main's name is: GoodBye
ClassA thinks Main's name is: GoodBye
Press any key to continue . . .

编辑3: 如果您在get和set块中未做任何特殊/额外的操作,则可以简化NameHolder类:

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