如果财产被宣布为私人财产怎么办?如何用C#来称呼它?

如果财产被宣布为私人财产怎么办?如何用C#来称呼它?,c#,visual-studio,properties,C#,Visual Studio,Properties,我的问题很简单:如果一个属性被声明为私有-如何称呼它 在java中,我们使用getter&setter,其中变量是私有的,而在C#中,属性是公共的;如果我把它设为私有,那么在主类中,它就不能被调用 这是我的代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace staticProperty {

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

在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.????
        }
    }
}
所以我理解属性就像getter setter,它应该是公共的


问题是,如果我将公共属性直接设置为不带变量,那么它应该是公共的,并被视为公共类或外部类,您可以使用与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都是公共的,但设置是私有的。

您可以使用反射调用类中的私有属性

我编写了下面的代码示例,您可以看看

 class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            PropertyInfo property = stu.GetType().GetProperty("Name", BindingFlags.Instance | BindingFlags.NonPublic);
            property.SetValue(stu,"test1");   //set value
            string value = property.GetValue(stu).ToString();//get value
            Console.WriteLine(value);
            Console.ReadKey();
        }

    }
    public class Student
    {
        private string Name { get; set; }
    }
输出:


Class1.name
将导致
StackOverflowException
(如果您可以访问它)。可以在类中设置或获取私有属性只需执行
公共字符串名称{get;set;}
这将创建一个带有公共getter和setter以及隐式私有支持字段的属性。property关键字不会终止封装OK我理解
 class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            PropertyInfo property = stu.GetType().GetProperty("Name", BindingFlags.Instance | BindingFlags.NonPublic);
            property.SetValue(stu,"test1");   //set value
            string value = property.GetValue(stu).ToString();//get value
            Console.WriteLine(value);
            Console.ReadKey();
        }

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