一般来说,字段、方法、静态方法、属性、属性和类(或静态变量)不会因语言而改变...虽然语法可能会因每种语言而改变,但它们的功能会有所不同您会期望跨语言(期望字段/数据成员等术语可以跨语言互换使用)
在 C# 中......
字段是存在于给定类实例的变量。
例如。
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field
protected int GetField
{
get
{
return _field;
}
}
}
字段具有“可见性”,这决定了其他类可以看到该字段,因此在上面的示例中,私有字段只能由包含它的类使用,但属性访问器提供子类对该字段的只读访问.
属性可以让您获取(有时称为访问器)或设置(有时称为修改器)字段的值...属性可以让您做一些事情,例如防止从类外部写入字段,更改字段的可见性(例如私有/受保护/公共)。 mutator 允许您在设置字段的值之前提供一些自定义逻辑
所以属性更像是获取/设置字段值但提供更多功能的方法
例如。
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field, but since it's visibility
// is protected only subclasses will know about this property
// (and through it the field) - The field and property in this case
// will be hidden from other classes.
protected int GetField
{
// This is an accessor
get
{
return _field;
}
// This is a mutator
set
{
// This can perform some more logic
if (_field != value)
{
Console.WriteLine("The value of _field changed");
_field = value;
OnChanged; // Call some imaginary OnChange method
} else {
Console.WriteLine("The value of _field was not changed");
}
}
}
}
类或静态变量是对类的所有实例都相同的变量。
因此,例如,如果您想要一个类的描述,该描述对于该类的所有实例都是相同的,并且可以通过使用该类来访问
例如。
public class BaseClass
{
// A static (or class variable) can be accessed from anywhere by writing
// BaseClass.DESCRIPTION
public static string DESCRIPTION = "BaseClass";
}
public class TestClass
{
public void Test()
{
string BaseClassDescription = BaseClass.DESCRIPTION;
}
}
在使用与属性相关的术语时要小心。在 C# 中,它是一个可以通过“装饰”类或方法来应用于其他类或方法的类,在其他上下文中,它可能只是引用一个类包含的字段。
// The functionality of this attribute will be documented somewhere
[Test]
public class TestClass
{
[TestMethod]
public void TestMethod()
{
}
}
有些语言没有像 C# 那样的“属性”(见上文)
希望这一切都有意义......不想让你超负荷!