C#扩展方法(Extend Method)

C#扩展方法(Extend Method)


在不更改原来类的基础上,为类添加方法。
1,扩展方法必须写静态类中
2,扩展方法必须是静态方法,虽然是静态方法,但是这个扩张方法是为对象扩展的,只能由对象调用。
public static class 类名
{
  public static 返回值 方法名(this 要扩展的类型 对象名[,参数列表])
  {

  }
}


static class Extend
{
public static TSource Test123<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{

foreach (TSource item in source)
{
if (predicate(item))
{
return (item);
}
}
throw new Exception("未找到!");
}
}


List<int> ints =new List<int> { 1,2,3,4,5,6 };

int nRet = ints.Test123(o => o > 5);//nRet=6

 

附:NHibernate的扩展类

using NHibernate;
using NHibernate.Type;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;

namespace NHibernate.Linq
{
public static class LinqExtensionMethods
{
public static IQueryable<T> Cacheable<T>(this IQueryable<T> query);
public static IQueryable<T> CacheMode<T>(this IQueryable<T> query, CacheMode cacheMode);
public static IQueryable<T> CacheRegion<T>(this IQueryable<T> query, string region);
public static T MappedAs<T>(this T parameter, IType type);
public static IQueryable<T> Query<T>(this ISession session);
public static IQueryable<T> Query<T>(this IStatelessSession session);
public static IQueryable<T> Query<T>(this ISession session, string entityName);
public static IQueryable<T> Query<T>(this IStatelessSession session, string entityName);
public static IQueryable<T> Timeout<T>(this IQueryable<T> query, int timeout);
public static IEnumerable<T> ToFuture<T>(this IQueryable<T> query);
public static IFutureValue<T> ToFutureValue<T>(this IQueryable<T> query);
public static IFutureValue<TResult> ToFutureValue<T, TResult>(this IQueryable<T> query, Expression<Func<IQueryable<T>, TResult>> selector);
}
}

转载于:https://www.cnblogs.com/SafeSimple/p/7819555.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值