什么是c#中的字段,为什么我要使用它
本文关键字:我要 为什么 字段 什么 | 更新日期: 2023-09-27 18:13:56
我正在学习c#,我想知道在c#类中字段的用途是什么?
例子using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Class_Constructor_II
{
class Fields
{
const double RandsInADollar = 7.8;
const double RandsInAEuro = 10.83
public double RandDollarConversion
{
get
{
return RandsInADollar / DollarRands;
}
set
{
DollarRands = value / RandsInADollar;
}
}
public double DollarRands
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
Fields f = new Fields();
f.DollarRands = 14500000;
Console.WriteLine(f.DollarRands);
}
}
}
没有比MSDN定义更好的了:
MSDN - Fields
如果微软决定再次改变他们的MSDN url,这里是:
字段是直接在类中声明的任何类型的变量或结构。字段是其包含类型的成员。
基本上,您将使用它们来包含在类内部使用的数据。需要存在于方法范围之外的东西,例如,具有较长的生命周期,例如对象的生命周期。
将字段设为公共通常被认为是一个坏主意——您会像在示例中那样使用属性。然而,封装规定了外部世界不需要知道你的类是如何做它所做的事情的——所以它可以使用字段来存储它需要做的任何事情的状态和值。
查看此字段的class wide变量字段