在.net 3.5中我们可以利用新特性“扩展方法”在任何类上非常方面简单的实现ToJSON(Javascript object Notation)方法:
假如我有一个简单的类,使用“自动属性”方式定义:
采用如下方法初始化我的对象集合,通过调用他的ToJOSN()扩展方法,我们就可以得到该集合的JSON字符串。
这是不是有点像调用.net内置的ToString()方法一样?唯一的区别就是他返回的字符串是预定义的,可以在AJAX使用的Javascript对象。
下面再来看看如何实现ToJSON扩展方法:
在.net 3.5中实现JSON非常方便,我只需要使用.net 3.5 System.Web.Script.Serialization 命名空间下的JavaScriptSerializer 类就可以了。
然后我们就可以在任何对象上调用其ToJSON扩展方了。
------------------------------------------------------------------------------
我们可以使用Linq的特性非常方便的操作文本文件的文本,并且很方面获取我们想要的文本数据,请看例子
internal class QueryWithRegEx
{
public static void GetFileWithRegex()
{
// 要搜索的路径
string startFolder = @"G:"Program Files"Microsoft Visual Studio 9.0"";
// 获取当前目录下的所有文件信息
IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder);
// 创建正则表达式
System.Text.RegularExpressions.Regex searchTerm =
new System.Text.RegularExpressions.Regex(@"Visual (Basic|C#|C"+"+|J#|SourceSafe)");
//并找出匹配正则表达式条件的html文件,并获取其文件名和匹配到的文字
var queryMatchingFiles =
from file in fileList
where file.Extension == ".htm"
let fileText = System.IO.File.ReadAllText(file.FullName)
let matches = searchTerm.Matches(fileText)
where searchTerm.Matches(fileText).Count > 0
select new
{
name = file.FullName,
matchedWords = from System.Text.RegularExpressions.Match match in matches
select match.Value
};
// Execute the query.
Console.WriteLine("The term ""{0}"" was found in:", searchTerm.ToString());
foreach (var v in queryMatchingFiles)
{
//打印所有匹配的文件名
string s = v.name.Substring(startFolder.Length - 1);
Console.WriteLine(s);
//打印所有匹配到的文本
foreach (var v2 in v.matchedWords)
{
Console.WriteLine(" " + v2);
}
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// Get All file handle in path
static IEnumerable<System.IO.FileInfo> GetFiles(string path)
{
if (!System.IO.Directory.Exists(path))
throw new System.IO.DirectoryNotFoundException();
string[] fileNames = null;
List<System.IO.FileInfo> files = new List<System.IO.FileInfo>();
fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);
foreach (string name in fileNames)
{
files.Add(new System.IO.FileInfo(name));
}
return files;
}
}
从这个例子除了使用到Linq和Regex,还是用到了let字句,从中我们可以体会出C#3.0带有函数式编程特征的新语法的威力!
下篇文章,我会单独举例说明let字句的使用。
--------------------------------------------------
在一个查询表达中,有时我们需要保存子表示式的处理结果以备后面的查询字句使用,尤其在做多层嵌套查询的时候,这时,我们就可以使用let字句来成这个任务,let字句会创建一个新的局部变量,并根据你提供的表达式初始化变量:
举例说明:
class LetSample
{
static void Main()
{
string[] strings =
{
"A penny saved is a penny earned.",
"The early bird catches the worm.",
"The pen is mightier than the sword."
};
// Split the sentence into an array of words
// and select those whose first letter is a vowel.
var earlyBirdQuery =
from sentence in strings
let words = sentence.Split(' ')
from word in words
let w = word.ToLower()
where w[0] == 'a' || w[0] == 'e'
|| w[0] == 'i' || w[0] == 'o'
|| w[0] == 'u'
select word;
// Execute the query.
foreach (var v in earlyBirdQuery)
{
Console.WriteLine("\"{0}\" starts with a vowel", v);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
"A" starts with a vowel
"is" starts with a vowel
"a" starts with a vowel
"earned." starts with a vowel
"early" starts with a vowel
"is" starts with a vowel
*/
再来一个对csv文件内容排序的例子
public class SortLines
{
static void Main()
{
// Create an IEnumerable data source
string[] scores = System.IO.File.ReadAllLines(@"http://www.cnblogs.com/../scores.csv");
// Change this to any value from 0 to 4.
int sortField = 1;
Console.WriteLine("Sorted highest to lowest by field [{0}]:", sortField);
// Demonstrates how to return query from a method.
// The query is executed here.
foreach (string str in RunQuery(scores, sortField))
{
Console.WriteLine(str);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// Returns the query variable, not query results!
static IEnumerable<string> RunQuery(IEnumerable<string> source, int num)
{
// Split the string and sort on field[num]
var scoreQuery = from line in source
let fields = line.Split(',')
orderby fields[num] descending
select line;
return scoreQuery;
}
}
-----------------------------------------------
linq不是扩展类
是扩展方法
扩展方法+隐式类型
扩展方法+隐式类型+lambda表达式
C#3.5的新内容是
1.扩展方法
2.隐式类型
3.lambda表达式
4.LINQ = 扩展方法+隐式类型+lambda表达式
using System.Linq;
using System.Text;
using System;
namespace CustomExtensions
{
//Extension methods must be defined in a static class
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
namespace Extension_Methods_Simple
{
//Import the extension method namespace.
using CustomExtensions;
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
// Call the method as if it were an
// instance method on the type. Note that the first
// parameter is not specified by the calling code.
int i = s.WordCount();
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}
这个是扩展方法
int i = s.WordCount => CustomExtensions.StringExtension.WordCount(i)
静态类 静态方法!
编译器帮你完成了
原来我们 一般都是用 普通类+静态方法!
这个技术是C语言实现OOP的技术
string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
LINQ方法
var upperLowerWords =
from w in words
select new { Upper = w.ToUpper(), Lower = w.ToLower() };
///
from w in words
where w.length() > 3 == => System.Linq.where(this, bool) ===> List<T> System.Linq.where(words, w.length() > 3) ===> C#3.5中Linq对List<T>扩展方法
select new { Upper = w.ToUpper(), Lower = w.ToLower() };
=====>
List<string> upperLowerWords = new List<string>();
foreach ( var w in words) => C#3.5中的隐式类型var ===> 在编译期间被compiled to System.String
{
if(w.length() > 3)
upperLowerWords.Add(new {w.ToUpper, w.ToLower()} ===> C# 3.5匿名对象构造器)
}
---信息源自网络收集,仅自己学习之用.