让我们把你的优秀和最喜欢的扩展方法列一个列表。
要求是必须发布完整的代码,以及如何使用它的示例和解释。
基于对这个主题的高度兴趣,我在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上实现和单元测试。
我在我的web项目中使用这些,主要是MVC。我为ViewData和TempData写了一些这样的代码
/// <summary>
/// Checks the Request.QueryString for the specified value and returns it, if none
/// is found then the default value is returned instead
/// </summary>
public static T QueryValue<T>(this HtmlHelper helper, string param, T defaultValue) {
object value = HttpContext.Current.Request.QueryString[param] as object;
if (value == null) { return defaultValue; }
try {
return (T)Convert.ChangeType(value, typeof(T));
} catch (Exception) {
return defaultValue;
}
}
这样我就可以写……
<% if (Html.QueryValue("login", false)) { %>
<div>Welcome Back!</div>
<% } else { %>
<%-- Render the control or something --%>
<% } %>
这是一个位图扩展,可以将位图转换为灰度;
public static Bitmap GrayScale(this Bitmap bitmap)
{
Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
Graphics g = Graphics.FromImage(newBitmap);
//the grayscale ColorMatrix
ColorMatrix colorMatrix = new ColorMatrix(new float[][] {
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix);
g.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, attributes);
g.Dispose();
return newBitmap;
}
示例用法:
Bitmap grayscaled = bitmap.GrayScale()
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。
在我的MiscUtil项目中有各种扩展方法(完整的源代码在那里可用-我不打算在这里重复它)。我最喜欢的,其中一些涉及其他类(如范围):
日期和时间——主要用于单元测试。我不确定我会在生产中使用它们:)
var birthday = 19.June(1976);
var workingDay = 7.Hours() + 30.Minutes();
范围和步进——非常感谢Marc Gravell的运算符使这成为可能:
var evenNaturals = 2.To(int.MaxValue).Step(2);
var daysSinceBirth = birthday.To(DateTime.Today).Step(1.Days());
比较:
var myComparer = ProjectionComparer.Create(Person p => p.Name);
var next = myComparer.ThenBy(p => p.Age);
var reversed = myComparer.Reverse();
参数检查:
x.ThrowIfNull("x");
LINQ to XML应用于匿名类型(或其他具有适当属性的类型):
// <Name>Jon</Name><Age>32</Age>
new { Name="Jon", Age=32}.ToXElements();
// Name="Jon" Age="32" (as XAttributes, obviously)
new { Name="Jon", Age=32}.ToXAttributes()
Push LINQ -在这里解释太长了,但是可以搜索一下。
有几次我发现自己想要Groovy的“安全导航”之类的东西。
从http://groovy.codehaus.org/Statements:
如果你在行走一个复杂的物体
图和不想要的
你可以抛出nullpointerexception
使用?。操作员而不是。来
执行导航。
Def foo = null Def bar =
.myMethod()断言条
= =零
那么,您认为为它添加扩展方法是一个好主意吗?
喜欢的东西:
obj.SafelyNavigate(x => x.SomeProperty.MaybeAMethod().AnotherProperty);
我认为即使它也会带来一些麻烦,这也很好。
如果你认为这是个好主意:
您认为值类型应该发生什么?,
返回默认吗?扔吗?,通过泛型约束禁用它?
吞咽NullReferenceException来实现它会太冒险吗?,
你有什么建议?,
遍历表达式树执行每个调用或成员访问似乎很困难,而且有点过度(如果可能的话),不是吗?
也许这只是一个坏主意:D,但我认为如果做得对,它是有用的。
如果没有类似的东西,你认为它有一些价值,我可能会给它一个机会,然后编辑答案。