一个有意思的类扩展 有效解决判空问题

public static class ClassExtensions
  {
    public static TResult GetProperty<TClass, TResult>(this TClass obj, Func<TClass, TResult> func) where TClass : class
    {
      if ((object) obj == null)
        return default (TResult);
      else
        return func(obj);
    }

    public static TResult GetProperty<TKey, TResult>(this IDictionary<TKey, TResult> dict, TKey key)
    {
      if (dict == null || !dict.ContainsKey(key))
        return default (TResult);
      else
        return dict[key];
    }

    public static TResult GetProperty<TKey, TValue, TResult>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue, TResult> func)
    {
      if (dict == null || !dict.ContainsKey(key))
        return default (TResult);
      TValue obj = dict[key];
      return func(obj);
    }

 

posted @ 2014-08-12 15:41  沐松  阅读(228)  评论(0编辑  收藏  举报