简体   繁体   English

如何使用 C# 中的 getter 和 setter 属性访问同一个 class 中的私有成员

[英]How to access the Private member in the same class using getter and setter property in C#

In the given code.在给定的代码中。 I want to access the private value in the other main class I read the value from the console and through this class want to display in the console我想访问其他主要 class 中的私有值 我从控制台读取值并通过此 class 想在控制台中显示

using System;

class Customer
{
    private string _customerAddress;

    public string CustomerAddress
    {
        get { return this._customerAddress; }   
        set { this._customerAddress = value; }
    }
    public void DisplayDetails()
    {
        Console.WriteLine("Hello World", CustomerAddress);
    }
}

I'm not sure what you mean, but if you want to give '_customerAddress' a value in your main form and then display the value with the 'DisplayDetails()' method then the following might help.我不确定你的意思,但如果你想在你的主窗体中给'_customerAddress'一个值,然后用'DisplayDetails()'方法显示该值,那么以下可能会有所帮助。

Main Form ==> make an Customer object and then give _customerAddress a value by simple doing this: Main Form ==> 创建一个 Customer object 然后通过简单的操作给 _customerAddress 一个值:

Customer customer = new Customer();
customer.CustomerAddress = "test";
customer.DisplayDetails();

You should also consider to give '_customerAddress' as a parameter in the constructor.您还应该考虑将“_customerAddress”作为构造函数中的参数。

In case you want to acces a private field from another class and display it in this class, then you should do the following:如果你想从另一个 class 访问私有字段并在这个 class 中显示它,那么你应该执行以下操作:

Step1: make a property in the other class like you did in the Customer class.第 1 步:像在客户 class 中所做的那样,在另一个 class 中创建一个属性。

Step 2: Make a another Display function and give to its parameter the object of the other class.第 2 步:制作另一个显示器 function 并将另一个 class 的参数 object 赋予其参数。

public class OtherClass
{
  private string message;

  public string Message
  {
     get{return this.message;}
     set{this.message = value;}
  }
}

call the property in your Customer Class:致电您的客户 Class 中的财产:

class Customer
{
    private string _customerAddress;

    public string CustomerAddress
    {
        get { return this._customerAddress; }   
        set { this._customerAddress = value; }
    }
    public void DisplayDetails()
    {
        Console.WriteLine("Hello World", CustomerAddress);
    }
    
    public void DisplayMessage(OtherClass otherClass) 
    {
        Console.WriteLine("Hello World",otherClass.Message);
    }
}

You can also make the method dat displays the message in the OtherClass Class and call that method in your Customer Class.您还可以使方法 dat 在 OtherClass Class 中显示消息,并在您的客户 Class 中调用该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM