【问题标题】:use of Set-only properties in csharp [duplicate]在 csharp 中使用仅设置属性 [重复]
【发布时间】:2014-11-05 05:42:59
【问题描述】:

我想知道为什么对成员的访问应该设置为仅拒绝读取其值。谁能解释一下什么时候使用这些?

提前致谢

【问题讨论】:

标签: c# properties


【解决方案1】:

如果您只想更改成员值,在这种情况下使用只写属性(SET)

例如:

class employee
{
    int id = 1;
    string name = "chandru";
    string dept = "IT";

    public string Name
    {
        get { return name; }
        private set { name = value; }       //Restricted to modify name to outer this calss
    }

    public string DEPT
    {
        set { dept = value; }
    }
    public void display()
    {
        Console.WriteLine("ID: {0} Name: {1} and Dept: {2}", id, name, dept);
    }
}
class Program
{
    static void Main(string[] args)
    {
        employee e = new employee();
        e.DEPT = "CSE";
        Console.WriteLine(e.Name);
        e.display();
      ///  e.Name = "Prakash";        //you cannot modify becoz of Access specifies as private

    }
}

set 属性仅用于更改您在客户端应用程序中想要的成员值...

注意: 据我所知,我更新了,如果有任何问题,请修改我的答案

【讨论】:

  • 嗯,这只会回答“如何”而不是“何时”或“为什么”。 “这是你在客户端应用程序中想要的”在我看来毫无意义。
猜你喜欢
  • 2017-06-22
  • 2012-03-13
  • 1970-01-01
  • 2018-04-28
  • 2016-08-29
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多