让我们把你的优秀和最喜欢的扩展方法列一个列表。
要求是必须发布完整的代码,以及如何使用它的示例和解释。
基于对这个主题的高度兴趣,我在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上实现和单元测试。
我不想添加任何已经说过的东西,所以这里有一些我没有提到的东西。(如果这太长了,对不起):
public static class MyExtensions
{
public static bool IsInteger(this string input)
{
int temp;
return int.TryParse(input, out temp);
}
public static bool IsDecimal(this string input)
{
decimal temp;
return decimal.TryParse(input, out temp);
}
public static int ToInteger(this string input, int defaultValue)
{
int temp;
return (int.TryParse(input, out temp)) ? temp : defaultValue;
}
public static decimal ToDecimal(this string input, decimal defaultValue)
{
decimal temp;
return (decimal.TryParse(input, out temp)) ? temp : defaultValue;
}
public static DateTime ToFirstOfTheMonth(this DateTime input)
{
return input.Date.AddDays(-1 * input.Day + 1);
}
// Intentionally returns 0 if the target date is before the input date.
public static int MonthsUntil(this DateTime input, DateTime targetDate)
{
input = input.ToFirstOfTheMonth();
targetDate = targetDate.ToFirstOfTheMonth();
int result = 0;
while (input < targetDate)
{
input = input.AddMonths(1);
result++;
}
return result;
}
// Used for backwards compatibility in a system built before my time.
public static DataTable ToDataTable(this IEnumerable input)
{
// too much code to show here right now...
}
}
我今天刚刚在博客上写了这个。它是INotifyPropertyChanged属性周围的强类型响应式包装器。
GetPropertyValues返回一个IObservable<T>的值,当它们改变时,从当前值开始。如果忽略当前值,可以对结果调用Skip(1)。
用法如下:
IObservable<int> values = viewModel.GetPropertyValues(x => x.IntProperty);
实现:
public static class NotifyPropertyChangeReactiveExtensions
{
// Returns the values of property (an Expression) as they change,
// starting with the current value
public static IObservable<TValue> GetPropertyValues<TSource, TValue>(
this TSource source, Expression<Func<TSource, TValue>> property)
where TSource : INotifyPropertyChanged
{
MemberExpression memberExpression = property.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException(
"property must directly access a property of the source");
}
string propertyName = memberExpression.Member.Name;
Func<TSource, TValue> accessor = property.Compile();
return source.GetPropertyChangedEvents()
.Where(x => x.EventArgs.PropertyName == propertyName)
.Select(x => accessor(source))
.StartWith(accessor(source));
}
// This is a wrapper around FromEvent(PropertyChanged)
public static IObservable<IEvent<PropertyChangedEventArgs>>
GetPropertyChangedEvents(this INotifyPropertyChanged source)
{
return Observable.FromEvent<PropertyChangedEventHandler,
PropertyChangedEventArgs>(
h => new PropertyChangedEventHandler(h),
h => source.PropertyChanged += h,
h => source.PropertyChanged -= h);
}
}
这个很有用:
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)
{
if (first == null)
throw new ArgumentNullException("first");
if (second == null)
throw new ArgumentNullException("second");
if (selector == null)
throw new ArgumentNullException("selector");
using (var enum1 = first.GetEnumerator())
using (var enum2 = second.GetEnumerator())
{
while (enum1.MoveNext() && enum2.MoveNext())
{
yield return selector(enum1.Current, enum2.Current);
}
}
}
它在。net 4.0中被添加到Enumerable类中,但是在3.5中使用它很方便。
例子:
var names = new[] { "Joe", "Jane", "Jack", "John" };
var ages = new[] { 42, 22, 18, 33 };
var persons = names.Zip(ages, (n, a) => new { Name = n, Age = a });
foreach (var p in persons)
{
Console.WriteLine("{0} is {1} years old", p.Name, p.Age);
}
下面是一个扩展方法,它适应Rick Strahl的代码(以及注释),使您不必在每次将字节数组或文本文件转换为字符串时猜测或阅读其字节顺序标记。
这个代码片段允许你简单地做:
byte[] buffer = File.ReadAllBytes(@"C:\file.txt");
string content = buffer.GetString();
如果你发现任何错误,请添加到评论中。请随意将它包含在Codeplex项目中。
public static class Extensions
{
/// <summary>
/// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.
/// Original article: http://www.west-wind.com/WebLog/posts/197245.aspx
/// </summary>
/// <param name="buffer">An array of bytes to convert</param>
/// <returns>The byte as a string.</returns>
public static string GetString(this byte[] buffer)
{
if (buffer == null || buffer.Length == 0)
return "";
// Ansi as default
Encoding encoding = Encoding.Default;
/*
EF BB BF UTF-8
FF FE UTF-16 little endian
FE FF UTF-16 big endian
FF FE 00 00 UTF-32, little endian
00 00 FE FF UTF-32, big-endian
*/
if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
encoding = Encoding.UTF8;
else if (buffer[0] == 0xfe && buffer[1] == 0xff)
encoding = Encoding.Unicode;
else if (buffer[0] == 0xfe && buffer[1] == 0xff)
encoding = Encoding.BigEndianUnicode; // utf-16be
else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
encoding = Encoding.UTF32;
else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
encoding = Encoding.UTF7;
using (MemoryStream stream = new MemoryStream())
{
stream.Write(buffer, 0, buffer.Length);
stream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
}
}