首页 > 解决方案 > 如果财产被声明为私有怎么办?如何在 C# 中调用它?

问题描述

我的问题很简单:如果一个属性被声明为私有 - 如何调用它?

在 java 中,我们使用 getter&setter,其中变量是私有的,但在 C# 中,属性是公共的;如果我将其设为私有,则在主类中,它不能被调用。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace staticProperty
{
    class Class1
    {
        private string name
        {
            get { return name; }
            set { name = value; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace staticProperty
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            c1.????
        }
    }
}

标签: c#visual-studioproperties

解决方案


您可以遵循与 Java 相同的布局

class Class1
{
    private string _name;

    public string getName(){
        return _name;
    }

    //methods to set the private variable anywhere in here.
}

或者更简洁

class Class1
{
   public string Name{ get; private set; }
}

在这两种情况下,getter 都是公开的,但设置是私有的。


推荐阅读