你最喜欢的 C# 扩展方法是什么?(codeplex.com/extensionoverflow)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/271398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)
提问by bovium
Let's make a list of answers where you post your excellent and favorite extension methods.
让我们列出一个答案列表,您可以在其中发布您的优秀和最喜欢的扩展方法。
The requirement is that the full code must be posted and a example and an explanation on how to use it.
要求是必须发布完整的代码以及示例和有关如何使用它的说明。
Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on Codeplex.
基于对这个主题的高度兴趣,我在Codeplex上设置了一个名为 extensionoverflow 的开源项目。
Please mark your answers with an acceptance to put the code in the Codeplex project.
请将您的答案标记为接受将代码放入 Codeplex 项目。
Please post the full sourcecode and not a link.
请发布完整的源代码而不是链接。
Codeplex News:
Codeplex 新闻:
24.08.2010 The Codeplex page is now here: http://extensionoverflow.codeplex.com/
24.08.2010 Codeplex 页面现在在这里:http://extensionoverflow.codeplex.com/
11.11.2008 XmlSerialize / XmlDeserializeis now Implementedand Unit Tested.
2008 年 11 月 11 日XmlSerialize / XmlDeserialize现已实施和单元测试。
11.11.2008 There is still room for more developers. ;-) Join NOW!
11.11.2008 仍有更多开发者的空间。;-)现在加入!
11.11.2008 Third contributer joined ExtensionOverflow, welcome to BKristensen
11.11.2008 第三位贡献者加入ExtensionOverflow,欢迎来到BKristensen
11.11.2008 FormatWithis now Implementedand Unit Tested.
11.11.2008 FormatWith现已实施和单元测试。
09.11.2008 Second contributer joined ExtensionOverflow. welcome to chakrit.
09.11.2008 第二个贡献者加入ExtensionOverflow。欢迎来到chakrit。
09.11.2008 We need more developers. ;-)
09.11.2008 我们需要更多的开发人员。;-)
09.11.2008 ThrowIfArgumentIsNullin now Implementedand Unit Testedon Codeplex.
回答by bovium
The ThrowIfArgumentIsNull is a nice way to do that null check we all should do.
ThrowIfArgumentIsNull 是进行我们都应该做的空检查的好方法。
public static class Extensions
{
public static void ThrowIfArgumentIsNull<T>(this T obj, string parameterName) where T : class
{
if (obj == null) throw new ArgumentNullException(parameterName + " not allowed to be null");
}
}
Below is the way to use it and it works on all classes in your namespace or wherever you use the namespace its within.
下面是使用它的方法,它适用于您命名空间中的所有类,或者您在其中使用命名空间的任何地方。
internal class Test
{
public Test(string input1)
{
input1.ThrowIfArgumentIsNull("input1");
}
}
It's ok to use this code on the CodePlexproject.
可以在CodePlex项目上使用此代码。
回答by chakrit
string.Format shortcut:
string.Format 快捷方式:
public static class StringExtensions
{
// Enable quick and more natural string.Format calls
public static string F(this string s, params object[] args)
{
return string.Format(s, args);
}
}
Example:
例子:
var s = "The co-ordinate is ({0}, {1})".F(point.X, point.Y);
For quick copy-and-paste go here.
如需快速复制和粘贴,请点击此处。
Don't you find it more natural to type "some string".F("param")
instead of string.Format("some string", "param")
?
难道你不觉得更自然的输入"some string".F("param")
,而不是string.Format("some string", "param")
?
For a more readablename, try one of these suggestion:
要获得更易读的名称,请尝试以下建议之一:
s = "Hello {0} world {1}!".Fmt("Stack", "Overflow");
s = "Hello {0} world {1}!".FormatBy("Stack", "Overflow");
s = "Hello {0} world {1}!".FormatWith("Stack", "Overflow");
s = "Hello {0} world {1}!".Display("Stack", "Overflow");
s = "Hello {0} world {1}!".With("Stack", "Overflow");
..
..
回答by sontek
gitorious.org/cadenzais a full library of some of the most useful extension methods I've seen.
gitorious.org/cadenza是我见过的一些最有用的扩展方法的完整库。
回答by CMS
Convert a double to string formatted using the specified culture:
将 double 转换为使用指定区域性格式化的字符串:
public static class ExtensionMethods
{
public static string ToCurrency(this double value, string cultureName)
{
CultureInfo currentCulture = new CultureInfo(cultureName);
return (string.Format(currentCulture, "{0:C}", value));
}
}
Example:
例子:
double test = 154.20;
string testString = test.ToCurrency("en-US"); // 4.20
回答by mlarsen
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);
}
}
Useful to parse a string into an Enum.
用于将字符串解析为 Enum。
public enum TestEnum
{
Bar,
Test
}
public class Test
{
public void Test()
{
TestEnum foo = "Test".EnumParse<TestEnum>();
}
}
Credit goes to Scott Dorman
幸得斯科特·多尔曼
--- Edit for Codeplex project ---
--- 编辑 Codeplex 项目---
I have asked Scott Dorman if he would mind us publishing his code in the Codeplex project. This is the reply I got from him:
我问过 Scott Dorman 是否介意我们在 Codeplex 项目中发布他的代码。这是我从他那里得到的答复:
Thanks for the heads-up on both the SO post and the CodePlex project. I have upvoted your answer on the question. Yes, the code is effectively in the public domain currently under the CodeProject Open License (http://www.codeproject.com/info/cpol10.aspx).
I have no problems with this being included in the CodePlex project, and if you want to add me to the project (username is sdorman) I will add that method plus some additional enum helper methods.
感谢您对 SO 帖子和 CodePlex 项目的提醒。我已经赞成你对这个问题的回答。是的,该代码目前在 CodeProject 开放许可 ( http://www.codeproject.com/info/cpol10.aspx)下有效地处于公共领域。
我将它包含在 CodePlex 项目中没有任何问题,如果您想将我添加到项目中(用户名是 sdorman),我将添加该方法以及一些额外的枚举辅助方法。
回答by TWith2Sugars
By all means put this in the codeplex project.
一定要把它放在 codeplex 项目中。
Serializing / Deserializing objects to XML:
将对象序列化/反序列化为 XML:
/// <summary>Serializes an object of type T in to an xml string</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="obj">Object to serialize</param>
/// <returns>A string that represents Xml, empty otherwise</returns>
public static string XmlSerialize<T>(this T obj) where T : class, new()
{
if (obj == null) throw new ArgumentNullException("obj");
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
/// <summary>Deserializes an xml string in to an object of Type T</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="xml">Xml as string to deserialize from</param>
/// <returns>A new object of type T is successful, null if failed</returns>
public static T XmlDeserialize<T>(this string xml) where T : class, new()
{
if (xml == null) throw new ArgumentNullException("xml");
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(xml))
{
try { return (T)serializer.Deserialize(reader); }
catch { return null; } // Could not be deserialized to this type.
}
}
回答by CMS
Examples:
例子:
DateTime firstDayOfMonth = DateTime.Now.First();
DateTime lastdayOfMonth = DateTime.Now.Last();
DateTime lastFridayInMonth = DateTime.Now.Last(DayOfWeek.Friday);
DateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);
DateTime lunchTime = DateTime.Now.SetTime(11, 30);
DateTime noonOnFriday = DateTime.Now.Next(DayOfWeek.Friday).Noon();
DateTime secondMondayOfMonth = DateTime.Now.First(DayOfWeek.Monday).Next(DayOfWeek.Monday).Midnight();
回答by sontek
Easily serialize objects into XML:
轻松将对象序列化为 XML:
public static string ToXml<T>(this T obj) where T : class
{
XmlSerializer s = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
s.Serialize(writer, obj);
return writer.ToString();
}
}
"<root><child>foo</child</root>".ToXml<MyCustomType>();
回答by TWith2Sugars
Another useful one for me:
另一个对我有用的:
/// <summary>
/// Converts any type in to an Int32
/// </summary>
/// <typeparam name="T">Any Object</typeparam>
/// <param name="value">Value to convert</param>
/// <returns>The integer, 0 if unsuccessful</returns>
public static int ToInt32<T>(this T value)
{
int result;
if (int.TryParse(value.ToString(), out result))
{
return result;
}
return 0;
}
/// <summary>
/// Converts any type in to an Int32 but if null then returns the default
/// </summary>
/// <param name="value">Value to convert</param>
/// <typeparam name="T">Any Object</typeparam>
/// <param name="defaultValue">Default to use</param>
/// <returns>The defaultValue if unsuccessful</returns>
public static int ToInt32<T>(this T value, int defaultValue)
{
int result;
if (int.TryParse(value.ToString(), out result))
{
return result;
}
return defaultValue;
}
Example:
例子:
int number = "123".ToInt32();
or:
或者:
int badNumber = "a".ToInt32(100); // Returns 100 since a is nan
回答by Jon Skeet
I have various extension methods in my MiscUtilproject (full source is available there - I'm not going to repeat it here). My favourites, some of which involve other classes (such as ranges):
我的MiscUtil项目中有各种扩展方法(那里有完整的源代码 - 我不打算在这里重复)。我最喜欢的,其中一些涉及其他类(例如范围):
Date and time stuff - mostly for unit tests. Not sure I'd use them in production :)
日期和时间的东西 - 主要用于单元测试。不确定我会在生产中使用它们:)
var birthday = 19.June(1976);
var workingDay = 7.Hours() + 30.Minutes();
Ranges and stepping - massive thanks to Marc Gravell for his operator stuffto make this possible:
范围和步进 - 非常感谢 Marc Gravell 的操作员东西使这成为可能:
var evenNaturals = 2.To(int.MaxValue).Step(2);
var daysSinceBirth = birthday.To(DateTime.Today).Step(1.Days());
Comparisons:
比较:
var myComparer = ProjectionComparer.Create(Person p => p.Name);
var next = myComparer.ThenBy(p => p.Age);
var reversed = myComparer.Reverse();
Argument checking:
参数检查:
x.ThrowIfNull("x");
LINQ to XML applied to anonymous types (or other types with appropriate properties):
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 - would take too long to explain here, but search for it.
推送 LINQ - 在这里解释会花费很长时间,但请搜索它。