让我们把你的优秀和最喜欢的扩展方法列一个列表。
要求是必须发布完整的代码,以及如何使用它的示例和解释。
基于对这个主题的高度兴趣,我在Codeplex上建立了一个名为extensionoverflow的开源项目。
请将您的回答标记为接受,以便将代码放入Codeplex项目。
请张贴完整的源代码,而不是一个链接。
Codeplex上新闻:
24.08.2010 Codeplex页面现在在这里:http://extensionoverflow.codeplex.com/
11.11.2008 XmlSerialize / XmlDeserialize现在是实现和单元测试。
11.11.2008仍有发展空间。;-)现在就加入!
11.11.2008第三位贡献者加入了ExtensionOverflow,欢迎加入BKristensen
11.11.2008 FormatWith现在是实现和单元测试。
09.11.2008第二个贡献者加入ExtensionOverflow。欢迎来到chakrit。
我们需要更多的开发人员。: -)
09.11.2008 ThrowIfArgumentIsNull现已在Codeplex上实现和单元测试。
讨厌这种代码?
CloneableClass cc1 = new CloneableClass ();
CloneableClass cc2 = null;
CloneableClass cc3 = null;
cc3 = (CloneableClass) cc1.Clone (); // this is ok
cc3 = cc2.Clone (); // this throws null ref exception
// code to handle both cases
cc3 = cc1 != null ? (CloneableClass) cc1.Clone () : null;
它有点笨拙,所以我用这个扩展替换它,我称之为CloneOrNull -
public static T CloneOrNull<T> (this T self) where T : class, ICloneable
{
if (self == null) return null;
return (T) self.Clone ();
}
用法如下:
CloneableClass cc1 = new CloneableClass ();
CloneableClass cc2 = null;
CloneableClass cc3 = null;
cc3 = cc1.CloneOrNull (); // clone of cc1
cc3 = cc2.CloneOrNull (); // null
// look mom, no casts!
请随意在任何地方使用这个!
我相信以前有人这样做过,但我发现自己经常使用这种方法(和更简单的导数):
public static bool CompareEx(this string strA, string strB, CultureInfo culture, bool ignoreCase)
{
return string.Compare(strA, strB, ignoreCase, culture) == 0;
}
您可以以多种方式编写它,但我喜欢它,因为它非常快速地统一了比较字符串的方法,同时节省了代码行数(或代码字符)。
GetMemberName允许在编译时安全的情况下获取带有成员名称的字符串。
public static string GetMemberName<T, TResult>(
this T anyObject,
Expression<Func<T, TResult>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
用法:
"blah".GetMemberName(x => x.Length); // returns "Length"
如果你没有实例,它会和一个非扩展静态方法一起出现:
public static string GetMemberName<T, TReturn>(
Expression<Func<T, TReturn>> expression)
where T : class
{
return ((MemberExpression)expression.Body).Member.Name;
}
当然,这个电话看起来并不漂亮:
ReflectionUtility.GetMemberName((string) s => s.Length); // returns "Length"
如果你愿意,可以用Codeplex。
用于ienumables的ForEach
public static class FrameworkExtensions
{
// a map function
public static void ForEach<T>(this IEnumerable<T> @enum, Action<T> mapFunction)
{
foreach (var item in @enum) mapFunction(item);
}
}
天真的例子:
var buttons = GetListOfButtons() as IEnumerable<Button>;
// click all buttons
buttons.ForEach(b => b.Click());
酷的例子:
// no need to type the same assignment 3 times, just
// new[] up an array and use foreach + lambda
// everything is properly inferred by csc :-)
new { itemA, itemB, itemC }
.ForEach(item => {
item.Number = 1;
item.Str = "Hello World!";
});
注意:
这与Select不同,因为Select期望函数返回转换为另一个列表的内容。
ForEach只是允许您为每个项执行一些东西,而不需要任何转换/数据操作。
我这样做,所以我可以在一个更函数式的风格编程,我很惊讶,列表有一个ForEach,而IEnumerable没有。
把这个放到codeplex项目中