using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp基础语法
{
class MyArray
{
private int[] items;
public MyArray(int capacity)
{
items = new int[capacity];
}
public void SetItem(int i ,int val)
{
items[i] = val;
}
public int GetItem(int i)
{
return items[i];
}
// 索引器
public int this[int index]
{
get
{
return items[index];
}
set
{
items[index] = value;
}
}
public int Size()
{
return this.items.Length;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp基础语法
{
class Program
{
static void Main(string[] args)
{
MyArray a = new MyArray(4);
a[0] = 12;
a[1] = 12;
a[2] = 12;
a[3] = 12;
for(int i = 0; i < a.Size(); i++)
{
Console.WriteLine(a[i] + " ");
}
a.SetItem(0, 16);
a.SetItem(0, 16);
a.SetItem(0, 16);
a.SetItem(0, 16);
for (int i = 0; i < a.Size(); i++)
{
Console.WriteLine(a.GetItem(i) + " ");
}
Console.WriteLine("\n");
}
}
}
2.重载操作符
MyFraction f1 =new MyFraction(1, 3);
MyFraction f2 = new MyFraction(2, 5);
MyFraction result = f1 *f2;
Console.WriteLine("结果: "+result);
MyFraction是一个类,也能支持乘法运算
在C#里面,可以重载操作符,
public static MyFraction operator *(MyFraction a, MyFraction b){
MyFraction result = new MyFraction();
result.num = a.num " b.num;
result.den = a.den * b.den;
return result;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp基础语法
{
class MyFraction
{
public int num = 0;
public int den = 1;
public MyFraction() { }
public MyFraction(int num ,int den)
{
this.num = num;
this.den = den;
}
public override string ToString()
{
return num + "/" + den;
}
// 重载乘法操作符
public static MyFraction operator *(MyFraction a,MyFraction b)
{
MyFraction res = new MyFraction();
res.num = a.num * b.num;
res.den = a.den * b.den;
return res;
}
// 普通写法
public static MyFraction Multiply(MyFraction a, MyFraction b)
{
MyFraction res = new MyFraction();
res.num = a.num * b.num;
res.den = a.den * b.den;
return res;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp基础语法
{
class Program
{
static void Main(string[] args)
{
// 定义两个分数 1/3 和 2/5
MyFraction f1 = new MyFraction(1, 3);
MyFraction f2 = new MyFraction(2, 5);
// 相乘
MyFraction res = f1 * f2;
Console.WriteLine("结果: " + res);
}
}
}