c# 教程
来源:互联网 发布:棉先生衣服怎么样 知乎 编辑:程序博客网 时间:2024/06/05 01:04
c# 属性 :用于访问类内成员变量(通过访问器)
例:
using System;namespace tutorialspoint{ class Student { private string code = "N.A"; private string name = "not known"; private int age = 0; // 声明类型为 string 的 Code 属性 public string Code { get { return code; } set { code = value; } } // 声明类型为 string 的 Name 属性 public string Name { get { return name; } set { name = value; } } // 声明类型为 int 的 Age 属性 public int Age { get { return age; } set { age = value; } } public override string ToString() { return "Code = " + Code +", Name = " + Name + ", Age = " + Age; } } class ExampleDemo { public static void Main() { // 创建一个新的 Student 对象 Student s = new Student(); // 设置 student 的 code、name 和 age s.Code = "001"; s.Name = "Zara"; s.Age = 9; Console.WriteLine("Student Info: {0}", s); // 增加年龄 s.Age += 1; Console.WriteLine("Student Info: {0}", s); Console.ReadKey(); } }}
c# 索引器:一般用于索引类内数组、字典等数据成员(通过访问器),使用“this”关键字进行定义
using System;namespace IndexerApplication{ class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; public IndexedNames() { for (int i = 0; i < size; i++) namelist[i] = "N. A."; } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = ""; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "Zara"; names[1] = "Riz"; names[2] = "Nuha"; names[3] = "Asif"; names[4] = "Davinder"; names[5] = "Sunil"; names[6] = "Rubic"; for ( int i = 0; i < IndexedNames.size; i++ ) { Console.WriteLine(names[i]); } Console.ReadKey(); } }}
按引用传递(函数)参数:在 C# 中,使用 ref 关键字声明引用参数。下面的实例演示了这点:
namespace CalculatorApplication{ class NumberManipulator { public void swap(ref int x, ref int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 temp 赋值给 y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int b = 200; Console.WriteLine("在交换之前,a 的值: {0}", a); Console.WriteLine("在交换之前,b 的值: {0}", b); /* 调用函数来交换值 */ n.swap(ref a, ref b); Console.WriteLine("在交换之后,a 的值: {0}", a); Console.WriteLine("在交换之后,b 的值: {0}", b); Console.ReadLine(); } }}
当上面的代码被编译和执行时,它会产生下列结果:
在交换之前,a 的值:100在交换之前,b 的值:200在交换之后,a 的值:200在交换之后,b 的值:100
按输出传递参数: 使用输出参数(关键字out) 可以从函数中返回值
阅读全文
0 0
- c#教程
- c#教程
- C#教程
- C#教程
- C#教程
- c# 教程
- C# 教程读书笔记
- MSDN C#教程整理
- 游戏开发教程c#
- C#教程--访问接口
- C# 事件 委托 教程
- C# 事件 委托 教程
- C#操作符教程
- C#教程电子书
- C# Namespace_C#教程
- C# Namespace_C#教程
- C#平台调用教程
- C# 类教程
- leetcode题解-5. Longest Palindromic Substring
- 宏一定要用大写
- OI中C++常数问题及其优化
- 字符串左旋
- 简明矩阵的还原
- c# 教程
- poi导出数据
- C++取得系统时间方法
- 慕课网学习项目之答答租车系统
- c语言三阶幻方问题(回溯)
- 原码, 反码, 补码 详解
- java 基础之数组各种操作
- 70-外传篇 1
- bzoj4917 [Lydsy六月月赛]Hash Killer IV