本文介绍了C#中的特殊getter和setter语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我发现用于在C#中创建getter和setter的方法。
我的问题是如何从实例访问getter和setter方法。
Following is the way I found that is used to create getter and setter in C#.
My question is how can I access getter and setter methods from instance.
class A
{
public int id { get; set; }
};
我试过以下但是id不起作用。
I have tried following but id does not work.
A a = new A();
a.getid();
推荐答案
A a = new A();
int id = a.id;
a.id = 666;
您所说的语法称为自动实现
或自动
属性,它只是一个简短形式:
The syntax you are talking of is called an autoimplemented
or automatic
property, and it's just a short form for:
private int _id;
public int id { get { return _id; } set { _id = value; }}
编译器生成 _id
支持字段。
BTW:标准是使用和初始大写字母foe属性,所以你的代码应该是:
The compiler generates the _id
backing field.
BTW: The standrad is to use and initial uppercase letter foe properties, so your code should really be:
class A
{
public int Id { get; set; }
}
...
A a = new A();
int id = a.Id;
a.Id = 666;
...
这篇关于C#中的特殊getter和setter语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!