c# - 如果财产被声明为私有怎么办?如何在 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.????
}
}
}
解决方案
您可以遵循与 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 都是公开的,但设置是私有的。
推荐阅读
- unix - awk:打印多个文件,将每个文件放入一个新文件夹。从输入文件中提取的文件夹名称
- julia - 为什么 Julia 中的微分方程给我这个 ODE 系统的“无匹配方法”错误?
- spring - Spring-Boot:在组件之间共享一个对象
- reactjs - 在 React with React Hooks 上使用动态导入视频
- twilio - Twilio:我如何在 24 小时后发送消息
- php - 在 where 子句中使用日期函数的 Codeigniter 查询
- excel - 我如何修复 application.counta 公式
- javascript - 如何使用 Vue Google Maps 显示我的当前位置
- html - 如何在 css 和 html 中将两个导航元素彼此分开?
- python-3.x - 从 ID 和序列的非结构化文件创建两列