using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Money m = new Money();
m.Amount = 30.00m;
Console.WriteLine(m.ToString());//输出$:30.00
//使用扩展方法
m.AddToMoney(1.00m);
Console.WriteLine(m.ToString());//输出$:31.00
Console.ReadKey();
}
}
public class Money {
private decimal amount;
public decimal Amount {
set { amount = value; }
get { return amount; }
}
public override string ToString()//重写ToString方法
{
return "$:" + amount.ToString();
}
}
//扩展方法
public static class MoneyExtension {
//this Money m 扩展方法的规则,告诉编译器这个方法是Money类型的一部分
public static void AddToMoney(this Money m, decimal d)
{
m.Amount += d;
}
}
}
分享标题:重写ToString与实现扩展方法
地址分享:
http://cdweb.net/article/phoopj.html