当前位置:首页 > c#定义
console.writeline(\ }
static void f(int x) {
console.writeline(\ }
static void f(double x) {
console.writeline(\ }
static void f(double x, dpuble y) {
console.writeline(\ }
static void main(){
f(); //调用f()
f(1); //调用f(int)
f(1.0); //调用f(double)
f(\调用f(object)
f((double)1); //调用f(double)
f((object)1); //调用f(object)
f(1, 1); //调用f(double, double) } }
如上例所示,总是通过自变量到参数类型的显式的类型转换,来选择特定方法。
1.6.6 其他函数成员
类的函数成员(function member)是包含可执行语句的成员。前面部分所描述的方法是主要的函数成员。这一节讨论其他几种c#支持的函数成员:构造函数、属性、索引器、事件、运算符、析构函数。
表1.8展示一个名为list的类,它实现一个可扩展的对象列表。这个类包含了最通用的几种函数成员的例子。
表1.8 类的函数成员示例
public class list {
const int defaultcapacity = 4; 常数
object[] items;
int count; 字段
(续表)
public list(): this(defaultcapacity) {}
public list(int capacity) {
items = new object[capacity]; } 构造函数
public int count {
get { return count; }
}
public string capacity { get {
return items.length; } set {
if (value < count) value = count;
if (value != items.length) {
object[] newitems = new object[value];
array.copy(items, 0, newitems, 0, count);
items = newitems; } } } 属性
public object this[int index] { get {
return items[index]; }
set {
items[index] = value;
onlistchange(); } } 索引器
public void add(object item) {
if (count == capacity) capacity = count * 2;
items[count] = item;
count++;
onchanged(); }
protected virtual void onchanged() {
if (changed != null) changed(this, eventargs.empty); }
public override bool equals(object other) {
return equals (this,other as list ); }
static bool equals ( list a,list b) {
if (a == null) return b == null;
if (b == null || a.count != b.count) return false;
共分享92篇相关文档