4.创建静态类,在其中定义一个泛型方法,实现查找数组元素功能。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program
{
class Program
{
static void Main(string[] args)
{
ArrayList ls = new ArrayList();
int[] a = { 1, 3, 5, 7, 9, 11 };
ls.AddRange(a);
int n = Convert.ToInt32(Console.ReadLine());
int m=Myclass.IndexOf(ls, n);
if (m != -1)
Console.WriteLine("{0}在数组中的位置为:{1}", n, m);
else
Console.WriteLine("{0}不在该数组中。",n);
Console.ReadKey();
}
}
class Myclass
{
public static int IndexOf<T>(T s, int n) where T : ArrayList
{
return s.IndexOf(n,0);
}
}
}
5.编写一个类似控制台应用,由控制台输出两个整数,输出较大的一个。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program
{
delegate int Mydelegate(int x,int y);
class Program
{
static void Main(string[] args)
{
Mydelegate d = (int a, int b) => a > b?a:b;
Console.WriteLine(d(2, 3));
Console.ReadKey(false);
}
}
}
6.下面控制台应用,利用string的扩展方法获取字符串中单词数量。输入下面代码,并编译运行,观察结果。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program
{
public static class Extensions
{
public static int GetWordCount(this string s)
{
int intCount = 0;
string[] strArray = s.Split(' ');
foreach (var str in strArray)
{
if (str.Length > 0)
{
intCount++;
}
}
return intCount;
}
}
class Program
{
static void Main(string[] args)
{
string s = "this is an apple";
Console.WriteLine("单词数量为{0}", s.GetWordCount());
Console.ReadLine();
}
}
}
7.仿照上面例子,设计一个扩展方法用于验证居民身份证合法性。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
namespace Program
{
public static class MyExtensions
{
public static bool Islegal(this string str)
{
Regex reg = new Regex(@"\d{17}[\d|X|x]|\d{15}");
if (reg.IsMatch(str))
return true;
else
return false;
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("请输入身份证号码:");
string str = Console.ReadLine();
if (str.Islegal())
Console.WriteLine("该身份证号码合法。");
else
Console.WriteLine("该身份证号码不合法.");
Console.ReadKey();
}
}
}