50,531
社区成员
发帖
与我相关
我的任务
分享
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
//据说这就是闭包。。。。
});
[code=Java]
引用楼上的例子大致就是这样子
[code=Java]
interface Predicate{
boolean predicate(String item);
}
IList<string> shortWords = ListUtil.Filter(words, new Predicate {
int maxLength = ......;
boolean predicate(String item) {
return item.length <= maxLength}
});
using System;
using System.Collections.Generic;
//工具类,其作为是通过"断言"来筛选元素
static class ListUtil
{
public static IList<T> Filter<T>(IList<T> source, Predicate<T> predicate)
{
List<T> ret = new List<T>();
foreach (T item in source)
{
if (predicate(item))
{
ret.Add(item);
}
}
return ret;
}
}
//测试类
class Test
{
static void Main()
{
Console.Write("Maximum length of string to include? ");
int maxLength = int.Parse(Console.ReadLine());
//===============区别部分==================
VariableLengthMatcher matcher = new VariableLengthMatcher(maxLength);
Predicate<string> predicate = new Predicate<string>(matcher.Match);
//===============区别部分==================
string[] words = { "111111111", "222", "33" };
IList<string> shortWords = ListUtil.Filter(words, predicate);
}
}
// 如果没有闭包,需要增加以下的类(匿名可以缓解这个情况,不过只能在简单场景下,C#1x没有JAVA有)
public class VariableLengthMatcher
{
int maxLength;
public VariableLengthMatcher(int maxLength)
{
this.maxLength = maxLength;
}
/// <summary>
/// Method used as the action of the delegate
/// </summary>
public bool Match(string item)
{
return item.Length <= maxLength;
}
}
using System;
using System.Collections.Generic; //工具类,其作为是通过"断言"来筛选元素
static class ListUtil
{
public static IList<T> Filter<T>(IList<T> source, Predicate<T> predicate)
{
List<T> ret = new List<T>();
foreach (T item in source)
{
if (predicate(item))
{
ret.Add(item);
}
} return ret;
}
} //测试类
class Test
{
static void Main()
{
Console.Write("Maximum length of string to include? ");
int maxLength = int.Parse(Console.ReadLine());
//===============区别部分==================
//由于通过闭包,直接使用到上下文,一句话替代了整个VariableLengthMatcher类
Predicate<string> predicate = delegate(string item){return item.Length <= maxLength;};
//===============区别部分==================
string[] words = { "111111111", "222", "33" };
IList<string> shortWords = ListUtil.Filter(words, predicate);
}
}