让我们把你的优秀和最喜欢的扩展方法列一个列表。
要求是必须发布完整的代码,以及如何使用它的示例和解释。
基于对这个主题的高度兴趣,我在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上实现和单元测试。
Sql server有~2000个参数的限制,如果你有10k个id并想要与它们连接的记录,这是一个痛苦。我写了这些方法,接受批量id列表,并像这样调用:
List<Order> orders = dataContext.Orders.FetchByIds(
orderIdChunks,
list => row => list.Contains(row.OrderId)
);
List<Customer> customers = dataContext.Orders.FetchByIds(
orderIdChunks,
list => row => list.Contains(row.OrderId),
row => row.Customer
);
public static List<ResultType> FetchByIds<RecordType, ResultType>(
this IQueryable<RecordType> querySource,
List<List<int>> IdChunks,
Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator,
Expression<Func<RecordType, ResultType>> projectionExpression
) where RecordType : class
{
List<ResultType> result = new List<ResultType>();
foreach (List<int> chunk in IdChunks)
{
Expression<Func<RecordType, bool>> filterExpression =
filterExpressionGenerator(chunk);
IQueryable<ResultType> query = querySource
.Where(filterExpression)
.Select(projectionExpression);
List<ResultType> rows = query.ToList();
result.AddRange(rows);
}
return result;
}
public static List<RecordType> FetchByIds<RecordType>(
this IQueryable<RecordType> querySource,
List<List<int>> IdChunks,
Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator
) where RecordType : class
{
Expression<Func<RecordType, RecordType>> identity = r => r;
return FetchByIds(
querySource,
IdChunks,
filterExpressionGenerator,
identity
);
}
public static class StringExtensions {
/// <summary>
/// Parses a string into an Enum
/// </summary>
/// <typeparam name="T">The type of the Enum</typeparam>
/// <param name="value">String value to parse</param>
/// <returns>The Enum corresponding to the stringExtensions</returns>
public static T EnumParse<T>(this string value) {
return StringExtensions.EnumParse<T>(value, false);
}
public static T EnumParse<T>(this string value, bool ignorecase) {
if (value == null) {
throw new ArgumentNullException("value");
}
value = value.Trim();
if (value.Length == 0) {
throw new ArgumentException("Must specify valid information for parsing in the string.", "value");
}
Type t = typeof(T);
if (!t.IsEnum) {
throw new ArgumentException("Type provided must be an Enum.", "T");
}
return (T)Enum.Parse(t, value, ignorecase);
}
}
将字符串解析为Enum很有用。
public enum TestEnum
{
Bar,
Test
}
public class Test
{
public void Test()
{
TestEnum foo = "Test".EnumParse<TestEnum>();
}
}
这要归功于斯科特·多尔曼
——编辑Codeplex项目——
我问过Scott Dorman,他是否介意我们在Codeplex项目中发布他的代码。我从他那里得到的回答是:
感谢你对SO帖子和CodePlex项目的提醒。我赞成你对这个问题的回答。是的,代码目前在CodeProject开放许可证(http://www.codeproject.com/info/cpol10.aspx)下有效地处于公共领域。
我没有问题,这被包括在CodePlex项目,如果你想把我添加到项目(用户名是sdorman),我会添加该方法加上一些额外的枚举助手方法。
对于Winform控件:
/// <summary>
/// Returns whether the function is being executed during design time in Visual Studio.
/// </summary>
public static bool IsDesignTime(this Control control)
{
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
return true;
}
if (control.Site != null && control.Site.DesignMode)
{
return true;
}
var parent = control.Parent;
while (parent != null)
{
if (parent.Site != null && parent.Site.DesignMode)
{
return true;
}
parent = parent.Parent;
}
return false;
}
/// <summary>
/// Sets the DropDownWidth to ensure that no item's text is cut off.
/// </summary>
public static void SetDropDownWidth(this ComboBox comboBox)
{
var g = comboBox.CreateGraphics();
var font = comboBox.Font;
float maxWidth = 0;
foreach (var item in comboBox.Items)
{
maxWidth = Math.Max(maxWidth, g.MeasureString(item.ToString(), font).Width);
}
if (comboBox.Items.Count > comboBox.MaxDropDownItems)
{
maxWidth += SystemInformation.VerticalScrollBarWidth;
}
comboBox.DropDownWidth = Math.Max(comboBox.Width, Convert.ToInt32(maxWidth));
}
IsDesignTime用法:
public class SomeForm : Form
{
public SomeForm()
{
InitializeComponent();
if (this.IsDesignTime())
{
return;
}
// Do something that makes the visual studio crash or hang if we're in design time,
// but any other time executes just fine
}
}
SetDropdownWidth用法:
ComboBox cbo = new ComboBox { Width = 50 };
cbo.Items.Add("Short");
cbo.Items.Add("A little longer");
cbo.Items.Add("Holy cow, this is a really, really long item. How in the world will it fit?");
cbo.SetDropDownWidth();
我忘了说,请随意在Codeplex上使用这些…
这是我写的唯一一个我经常使用的扩展。
它使得用System.Net.Mail发送电子邮件更容易一些。
public static class MailExtension
{
// GetEmailCreditial(out strServer) gets credentials from an XML file
public static void Send(this MailMessage email)
{
string strServer = String.Empty;
NetworkCredential credentials = GetEmailCreditial(out strServer);
SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };
client.Send(email);
}
public static void Send(this IEnumerable<MailMessage> emails)
{
string strServer = String.Empty;
NetworkCredential credentials = GetEmailCreditial(out strServer);
SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };
foreach (MailMessage email in emails)
client.Send(email);
}
}
// Example of use:
new MailMessage("info@myDomain.com","you@gmail.com","This is an important Subject", "Body goes here").Send();
//Assume email1,email2,email3 are MailMessage objects
new List<MailMessage>(){email1, email2, email}.Send();
我创建了一个扩展方法来在下拉菜单中选择一个项目。
下面是代码
public static class Utilities
{
public enum DropDownListSelectionType
{
ByValue,
ByText
}
public static void SelectItem(this System.Web.UI.WebControls.DropDownList drp, string selectedValue, DropDownListSelectionType type)
{
drp.ClearSelection();
System.Web.UI.WebControls.ListItem li;
if (type == DropDownListSelectionType.ByValue)
li = drp.Items.FindByValue(selectedValue.Trim());
else
li = drp.Items.FindByText(selectedValue.Trim());
if (li != null)
li.Selected = true;
}}
此方法可以由以下代码行调用,以按文本进行选择
DropDownList1.SelectItem("ABCD", Utilities.DropDownListSelectionType.ByText);
或者按值选择
DropDownList1.SelectItem("11", Utilities.DropDownListSelectionType.ByValue);
上面的代码不选择任何东西,如果它不能找到传递进来的文本/值。