成员定义
|
1.字段的定义 |
class MyClass
{
public int MyInt;
}
表示这个字段只能在 执行构造函数的过程中赋值,或者由初始化语句赋值
初始化时赋值
class MyClass
{
public readonly int MyInt = 2017;
}
class MyClass
{
public static int MyInt;
}
注意:静态字段必须通过定义他们的类来访问,不能通过实例化的对象来访问
上面的示例中,只能这样访问
MyClass.MyInt
|
2.定义方法 |
注意:用static修饰后,只能通过类访问,不能通过实例化的对象访问
使用关键字
注意:
如果使用了override,也可以使用 sealed 来指定 派生类中不能对这个方法进一步修改
|
3.定义属性 |
private int myInt;
public int MyInt
{
get{ return myInt * 3;}
set{ myInt = value / 3;}
}
注意:这里的只读和只写只适用于外部代码,类中的其他代码依旧能访问其中的数据
注意:value 关键字表示用户提供的属性值,其类型和属性相同,所以如果属性和字段使用相同的类型,就不用类型转换。
//类中MyClass
private int myInt;
public int MyInt
{
get{ return myInt;}
set
{
if(value >= 0 && value <= 10)
myInt = value;
}
}
//类外使用
MyClass myObj = new MyClass();
for(int i = -1; i < 1; i++)
{
myObj.MyInt = i;
}
上述代码中,如果赋给属性的值不满足 value >= 0 || value <= 10,也就是说使用了无效的值,该怎么办?
一般情况下,后两种处理方式较好,使用 4 的方法,代码如下
set
{
if (value >= 0 && value <= 10)
{
myInt = value;
}
else
{
throw (new ArgumentOutOfRangeException("MyIntProp", value,
"MyIntProp must be assigned a value between 0 and 10"));
}
}
private int myInt;
public int MyInt
{
public get { return myInt; } //error 因为访问器的级别和属性相同,所以错误(访问器访问级别更加严格)
set { myInt = value; }
}
理解:
首先第四条最容易想到,也是很合理的,毕竟是外围的决定内部的。
其次,既然第四条可以理解,那么如果只有一个访问器的时候,访问器访问级别等同属性,如果这个时候再去指 定更加严格的访问级别,那么为何不当初在属性上指定呢?
这条理解了,那么为什么必须同时具有get,set才能添加访问修饰符就更加明确了。
推理:
接口中属性是public的,那么如果接口中只有一个get或者set的时候,我们可以在继承中指明另一个访问器的属性。(接口中只有一个访问器,另一个可以在继承中指明访问级别)
但是如果接口中同时具有get,set,那么按照派生和继承的匹配性,这时候就不能这样再指定访问器的访问限制了。 (接口中有两个访问器,不能再指定访问器的访问级别)
public interface ISomeInterface
{
int TestProperty
{
// No access modifier allowed here
// because this is an interface.
get;
}
}
public class TestClass : ISomeInterface
{
public int TestProperty
{
// Cannot use access modifier here because
// this is an interface implementation.
get { return 10; }
// Interface property does not have set accessor,
// so access modifier is allowed.
protected set { }
}
}
private static int counter;
public static int Counter
{
get { return counter; }
}
public class Employee
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public class Manager : Employee
{
private string name;
// Notice the use of the new modifier:
public new string Name // use new to hide property in base class
{
get { return name; }
set { name = value + ", Manager"; }
}
}
public class Parent
{
public virtual int TestProperty
{
protected set { }
get { return 0; }
}
}
public class Kid : Parent
{
public override int TestProperty
{
protected set { }
get { return 0; }
}
}
abstract class Shape
{
public abstract double Area
{
get;
set;
}
}
class Square : Shape
{
public double side;
public override double Area
{
get
{
return side * side;
}
set
{
side = System.Math.Sqrt(value);
}
}
}
接口属性不具有函数体
当属性访问器中不需要其他访问逻辑时候,就可以使用自动属性,使代码更加简洁
public double TotalPurchases { get; set; }
有两个使用场景:
在接口中定义,继承接口的类就可以用了。
当有个字段不需要限制访问,为了编程习惯又不想写成公有字段,同时有懒得主动写那个字段名的时候,就使用自动属性吧。
|
【c#】定义类成员(字段、方法、属性)
最新推荐文章于 2025-06-05 17:11:48 发布