日期:2014-05-17  浏览次数:20465 次

泛型方法
public static T Get<TKey, T>(this Dictionary<TKey, T> dics, TKey key, Func<T> fetch)
  {
  if (dics.ContainsKey(key))
  {
  return dics[key];
  }
  else
  {
  T value = fetch();
  dics[key] = value;
  return value;
  }
  }
这部分代码,不是很懂,特别是红色标注部分的参数不明白,希望可以列举参数的所表达的意思。谢谢!

------解决方案--------------------
这涉及到一个概念:扩展方法。

用this修饰的参数,使得你可以在C#中视作它的成员方法。

比如:void foo(this string x, int y);
那么如果有一个字符串变量,你可以这么调用 "hello world".foo(1);
看上去foo像string的成员方法一样。
------解决方案--------------------
public static T Get<TKey, T>(this Dictionary<TKey, T> dics, TKey key, Func<T> fetch);
TKey、T 这个你可以理解为不指定类型。

也就是这里没给这个Dictionary或者是这个get方法赋值 当你调用的时候可以先给他置顶一个类型 然后就可以按照常规的调用方式去使用它 好处是 增加了代码的复用性!