using System;
namespace CalculatorApplication
{
public static class ExtensionString
{
//向 String 类扩展一个统计单词数量的方法
//1、扩展类必须为静态类,扩展方法必须为静态方法。
//2、扩展方法的第1个形参开头必须使用 “this” 关键字然后再填写扩展的目标类。
//3、如果需要接收参数则从第2个参数开始算起,第1个参数在真正调用方法时是隐藏的。
public static int CountWord(this String str)
{
return str.Split(' ').Length;
}
}
class NumberManipulator
{
//提供给输出参数的变量不需要赋值。当需要从一个参数没有指定初始值的方法中返回值时,输出参数特别有用。请看下面的实例,来理解这一点:
public void getValues(out int x, out int y)
{
Console.WriteLine("请输入第一个值: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入第二个值: ");
y = Convert.ToInt32(Console.ReadLine());
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a, b;
/* 调用函数来获取值 */
n.getValues(out a, out b);
Console.WriteLine("在方法调用之后,a 的值: {0}", a);
Console.WriteLine("在方法调用之后,b 的值: {0}", b);
Console.WriteLine("单词数量:" + "Hello World".CountWord()); //没有参数
Console.ReadLine();
}
}
}