新­科医­院治甲亢轻度甲亢需要治疗吗好吗

最新养殖技术'中华草龟'的书到哪里有的买_百度知道ღ_阳光总在风雨后,说的太好了!
共 1716 浏览 4 回帖&&
发帖: 100 篇
在线时长: 134 小时
安家基金:
ღ_阳光总在风雨后,说的太好了!
' + newItem.onLineCount+ '' + newItem.name + '';
NTES.ajax.importJs(url, function() {
var len = hotLive.
if (hotLive != '' && len != 0){
for (var i = 0; i < len-1; i++) {
var boboItem = hotLive[i],
isLive = boboItem.live,
liveHref = isLive ? boboItem.liveUrl + boboStatTag : "/" + boboStatTag,
boboLiveStat = isLive ? '' : '',
boboHtml = '';
html += boboH
if(i === 0){
html += newH
NTES(".bobo-list").attr("innerHTML", function() {
return this.innerHTML +
}, "utf-8");
}, "utf-8");
积分: 99986
发帖: 1808 篇
在线时长: 3439 小时
安家基金:
写的好赞哦
亲,可以来参加活动啊,而且有小礼品哦
网易论坛,天天相伴
吾独爱莲,出淤泥而不染,濯清涟而不妖
积分: 3359
发帖: 771 篇
在线时长: 205 小时
安家基金:
积分: 34149
发帖: 2034 篇
在线时长: 3142 小时
安家基金:
网易论坛,天天相伴
论天下大事,品清茶一杯
积分: 37108
发帖: 507 篇
在线时长: 4040 小时
安家基金:
每30秒自动保存一次内容
房产论坛活动专区
置业俱乐部
24小时热帖榜厦门家长注意!很多中小学生得了一种“站立就会脑供血不全&#34;的病!医院专家详解
较昨日:0名
搜狐我来说两句官方微博和微信
精彩评论 尽在掌握什么是最好的或最有趣的扩展方法您使用 &#39; 见过吗?
我开始真正爱...我不知道是否她有偶然发现一个人,真的吹了他们的心,或只是发现聪明。
我今天写了一个示例:
编辑由于到其他用户的评论:
public static numerable&int& To(this int fNumber, int toNumber) {
while (fromNumber & toNumber) {
yield return fromN
fromNumber++;
这允许写入作为 foreach 循环的循环:
foreach (int x in 0.To(16)) {
Console.WriteLine(Math.Pow(2, x).ToString());
我等不及要看看其他的例子 !享受 !
解决方法 1:
这是得到了一些游戏离我最近的一个:
public static IDisposable Tag(this HtmlHelper html, string tagName)
if (html == null)
throw new ArgumentNullException("html");
Action&string& a = tag =& html.Write(String.Format(tag, tagName));
a("&{0}&");
return new Memento(() =& a("&/{0}&"));
使用类似:
using (Html.Tag("ul"))
this.Model.ForEach(item =& using(Html.Tag("li")) Html.Write(item)));
using(Html.Tag("li")) Html.Write("new");
纪念是一个方便的类:
public sealed class Memento : IDisposable
private bool Disposed { }
private Action Action { }
public Memento(Action action)
if (action == null)
throw new ArgumentNullException("action");
void IDisposable.Dispose()
if (Disposed)
throw new ObjectDisposedException("Memento");
Disposed =
并完成依赖项:
public static void Write(this HtmlHelper html, string content)
if (html == null)
throw new ArgumentNullException("html");
html.ViewContext.HttpContext.Response.Write(content);
解决方法 2:
完整的解决方案是太大,无法放在这儿,但我写了一系列的扩展方法,使您能够轻松地将数据表中转换为 CSV。
public static String ToCSV(this DataTable dataTable)
return dataTable.ToCSV(null, COMMA, true);
public static String ToCSV(this DataTable dataTable, String qualifier)
return dataTable.ToCSV(qualifier, COMMA, true);
private static String ToCSV(this DataTable dataTable, String qualifier, String delimiter, Boolean includeColumnNames)
if (dataTable == null)
if (qualifier == delimiter)
throw new InvalidOperationException(
"The qualifier and the delimiter are identical. This will cause the CSV to have collisions that might result in data being parsed incorrectly by another program.");
var sbCSV = new StringBuilder();
var delimiterToUse = delimiter ?? COMMA;
if (includeColumnNames)
sbCSV.AppendLine(dataTable.Columns.GetHeaderLine(qualifier, delimiterToUse));
foreach (DataRow row in dataTable.Rows)
sbCSV.AppendLine(row.ToCSVLine(qualifier, delimiterToUse));
return sbCSV.Length & 0 ? sbCSV.ToString() :
private static String ToCSVLine(this DataRow dataRow, String qualifier, String delimiter)
var colCount = dataRow.Table.Columns.C
var rowValues = new String[colCount];
for (var i = 0; i & colC i++)
rowValues[i] = dataRow[i].Qualify(qualifier);
return String.Join(delimiter, rowValues);
private static String GetHeaderLine(this DataColumnCollection columns, String qualifier, String delimiter)
var colCount = columns.C
var colNames = new String[colCount];
for (var i = 0; i & colC i++)
colNames[i] = columns[i].ColumnName.Qualify(qualifier);
return String.Join(delimiter, colNames);
private static String Qualify(this Object target, String qualifier)
return qualifier + target +
在一天结束时,您可以这样称呼它:
someDataTable.ToCSV(); //Plain old CSV
someDataTable.ToCSV("\""); //Double quote qualifier
someDataTable.ToCSV("\"", "\t"); //Tab delimited
解决方法 3:
好,这不正是聪明,但我修改----OrDefault 方法使您可以指定默认项内联的而不是检查 null,稍后在您的代码:
public static T SingleOrDefault&T& ( this IEnumerable&T& source,
Func&T, bool& action, T theDefault )
T item = source.SingleOrDefault&T&(action);
if (item != null)
return theD
其令人难以置信的简单但真正帮助清理那些空的检查。当您的 UI 预计 X 锦标赛的系统,这样的项的列表或游戏玩家插槽,并且您想要显示"空的座位时,最好使用。
使用方法:
return jediList.SingleOrDefault(
j =& j.LightsaberColor == "Orange",
new Jedi() { LightsaberColor = "Orange", Name = "DarthNobody");
解决方法 4:
我喜欢用的两个是 InserWhere&T> 和 RemoveWhere&T> 扩展方法,已经写了。使用 ObservableCollections 在 WPF 和 Silverlight 经常需要修改有序列的表,而不会重新创建它们。这些方法允许插入和删除依法提供的函数,所以我。OrderBy() 不需要为 re-called。
/// &summary&
/// Removes all items from the provided &paramref name="list"/& that match the&paramref name="predicate"/& expression.
/// &/summary&
/// &typeparam name="T"&The class type of the list items.&/typeparam&
/// &param name="list"&The list to remove items from.&/param&
/// &param name="predicate"&The predicate expression to test against.&/param&
public static void RemoveWhere&T&(this IList&T& list, Func&T, bool& predicate)
T[] copy = new T[] { };
Array.Resize(ref copy, list.Count);
list.CopyTo(copy, 0);
for (int i = copy.Length - 1; i &= 0; i--)
if (predicate(copy[i]))
list.RemoveAt(i);
/// &summary&
/// Inserts an Item into a list at the first place that the &paramref name="predicate"/& expression fails.
If it is true in all cases, then the item is appended to the end of the list.
/// &/summary&
/// &typeparam name="T"&&/typeparam&
/// &param name="list"&&/param&
/// &param name="obj"&&/param&
/// &param name="predicate"&The sepcified function that determines when the &paramref name="obj"/& should be added. &/param&
public static void InsertWhere&T&(this IList&T& list, T obj, Func&T, bool& predicate)
for (int i = 0; i & list.C i++)
// When the fuction first fails it inserts the obj paramiter.
// For example, in a list myList of ordered Int32's {1,2,3,4,5,10,12}
// Calling myList.InsertWhere( 8, x =& 8 & x) inserts 8 once the list item becomes greater then or equal to it.
if(!predicate(list[i]))
list.Insert(i, obj);
list.Add(obj);
编辑:Talljoe RemoveWhere/出现,仓卒地修建了,作出有明显的改善。与 ~ 3mill 项目,除每三个,新版本毫秒仅为 50 ~ (少然后 10 如果它可以调用 List.RemoveAll !) 相对于 RemoveWhere 的多秒 (我厌倦了等待它)。
这是他大大改进的版本,再次感谢 !
public static void RemoveAll&T&(this IList&T& instance, Predicate&T& predicate)
if (instance == null)
throw new ArgumentNullException("instance");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (instance is T[])
throw new NotSupportedException();
var list = instance as List&T&;
if (list != null)
list.RemoveAll(predicate);
int writeIndex = 0;
for (int readIndex = 0; readIndex & instance.C readIndex++)
var item = instance[readIndex];
if (predicate(item))
if (readIndex != writeIndex)
instance[writeIndex] =
if (writeIndex != instance.Count)
for (int deleteIndex = instance.Count - 1; deleteIndex &= writeI --deleteIndex)
instance.RemoveAt(deleteIndex);
解决方法 5:
我公司拥有多种 .Debugify 用于倾销到日志文件中的对象的扩展方法。例如,这里是我的字典 debugify (我有这些列表、 数据表、 参数数组,等等):
public static string Debugify&TKey, TValue&(this Dictionary&TKey, TValue& dictionary) {
string Result = "";
if (dictionary.Count & 0) {
StringBuilder ResultBuilder = new StringBuilder();
int Counter = 0;
foreach (KeyValuePair&TKey, TValue& Entry in dictionary) {
Counter++;
ResultBuilder.AppendFormat("{0}: {1}, ", Entry.Key, Entry.Value);
if (Counter % 10 == 0) ResultBuilder.AppendLine();
Result = ResultBuilder.ToString();
在这里是一个用于 DbParameterCollection (适用于倾销到日志文件的数据库调用):
public static string Debugify(this DbParameterCollection parameters) {
List&string& ParameterValuesList = new List&string&();
foreach (DbParameter Parameter in parameters) {
string ParameterName, ParameterV
ParameterName = Parameter.ParameterN
if (Parameter.Direction == ParameterDirection.ReturnValue)
if (Parameter.Value == null || Parameter.Value.Equals(DBNull.Value))
ParameterValue = "NULL";
switch (Parameter.DbType)
case DbType.String:
case DbType.Date:
case DbType.DateTime:
case DbType.Guid:
case DbType.Xml:
ParameterValue
= "'" + Parameter
.ToString()
.Replace(Environment.NewLine, "")
.Left(80, "...") + "'"; // Left... is another nice one
ParameterValue = Parameter.Value.ToString();
if (Parameter.Direction != ParameterDirection.Input)
ParameterValue += " " + Parameter.Direction.ToString();
ParameterValuesList.Add(string.Format("{0}={1}", ParameterName, ParameterValue));
return string.Join(", ", ParameterValuesList.ToArray());
示例结果:
Log.DebugFormat("EXEC {0} {1}", procName, params.Debugify);
// EXEC spProcedure @intID=5, @nvName='Michael Haren', @intRefID=11 OUTPUT
请注意,如果您调用此 后 您的数据库调用,你就会得到太填写的输出参数。我呼吁这行,其中包含 SP 名称,所以我可以复制/粘贴短程调用进行调试。
又靓又容易而不会中断我的代码生成,这些使我的日志文件。
解决方法 6:
这里是我一起黑客的攻击,所以觉得自由吹毛求疵了。它采用整数 (有序) 列表,并返回字符串的连续范围的列表。比如:
1,2,3,7,10,11,12
"1-3","7","10-12"
(静态的类) 内的功能:
public static IEnumerable&string& IntRanges(this IEnumerable&int& numbers)
int rangeStart = 0;
int previous = 0;
if (!numbers.Any())
rangeStart = previous = numbers.FirstOrDefault();
foreach (int n in numbers.Skip(1))
if (n - previous & 1) // sequence break - yield a sequence
if (previous & rangeStart)
yield return string.Format("{0}-{1}", rangeStart, previous);
yield return rangeStart.ToString();
rangeStart =
previous =
if (previous & rangeStart)
yield return string.Format("{0}-{1}", rangeStart, previous);
yield return rangeStart.ToString();
使用示例:
this.WeekDescription = string.Join(",", from.WeekPattern.WeekPatternToInts().IntRanges().ToArray());
此代码用于将数据从一个 DailyWTF 值得时间表应用程序转换。WeekPattern 是一个字符串""… … 中存储的位掩码。WeekPatternToInts() 转换的例子为 &int&,在此情况下 [3,4,6,7,8],成为"3-4-8"。它为用户提供了紧凑的讲座发生的学术周范围说明。
解决方法 7:
一对将转换为整数的基地 36 strings(!) 扩展方法:
public static int ToBase10(this string base36)
if (string.IsNullOrEmpty(base36))
int value = 0;
foreach (var c in base36.Trim())
value = value * 36 + c.ToBase10();
public static int ToBase10(this char c)
if (c &= '0' && c &= '9')
return c - '0';
c = char.ToUpper(c);
if (c &= 'A' && c &= 'Z')
return c - 'A' + 10;
(一些天才决定在数据库中存储的数字的最佳方法是进行编码的字符串。小数占用太多的空间。六角较好,但不是使用 G Z 字符。很明显你延长基地-16 到基地 36 !)
解决方法 8:
我写了一系列的扩展方法,使它更易于操作 ADO。净的对象和方法:
创建一条指令中的 DbConnection DbCommand:
public static DbCommand CreateCommand(this DbConnection connection, string commandText)
DbCommand command = connection.CreateCommand();
mandText = commandT
将参数添加到 DbCommand 中:
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType)
DbParameter p = AddParameter(command, name, dbType, 0, ParameterDirection.Input);
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType, object value)
DbParameter p = AddParameter(command, name, dbType, 0, ParameterDirection.Input);
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType, int size)
return AddParameter(command, name, dbType, size, ParameterDirection.Input);
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType, int size, ParameterDirection direction)
DbParameter parameter = command.CreateParameter();
parameter.ParameterName =
parameter.DbType = dbT
parameter.Direction =
parameter.Size =
command.Parameters.Add(parameter);
访问 DbDataReader 字段名称,而不是索引:
public static DateTime GetDateTime(this DbDataReader reader, string name)
int i = reader.GetOrdinal(name);
return reader.GetDateTime(i);
public static decimal GetDecimal(this DbDataReader reader, string name)
int i = reader.GetOrdinal(name);
return reader.GetDecimal(i);
public static double GetDouble(this DbDataReader reader, string name)
int i = reader.GetOrdinal(name);
return reader.GetDouble(i);
public static string GetString(this DbDataReader reader, string name)
int i = reader.GetOrdinal(name);
return reader.GetString(i);
其他 (无关联) 的扩展方法允许我 DragMove 上执行的操作 (如在 WPF) WinForms 窗体和控件, 。
解决方法 9:
我在这里看到的扩展方法的大多数示例违背了最佳实践。扩展方法功能非常强大,但应谨慎使用。以我的经验,通常将星级酒店大多数的这些老式的语法与静态佣工/实用程序类。
有话要说,扩展方法的枚举,它不可能再有方法。如果在同一命名空间中,为您的枚举和同一程序集中定义它们,它们透明地工作。
解决方法 10:
虽然很简单,我觉得这是非常有用的因为拿出一个完整的结果页的一个设置 10 亿倍的项目:
public static class QueryableExtensions
public static IQueryable&T& Page(this IQueryable&T& query, int pageNumber, int pageSize)
int skipCount = (pageNumber-1) * pageS
query = query.Skip(skipCount);
query = query.Take(pageSize);
解决方法 11:
我不是一个风扇的 INotifyPropertyChanged 接口要求属性名称作为字符串进行传递。我想要检查在编译时,我只提出和处理属性更改为存在的属性的强类型的方式。我要做,使用以下代码:
public static class INotifyPropertyChangedExtensions
public static string ToPropertyName&T&(this Expression&Func&T&& @this)
var @return = string.E
if (@this != null)
var memberExpression = @this.Body as MemberE
if (memberExpression != null)
@return = memberExpression.Member.N
在类实现 INotifyPropertyChanged 此帮助器方法包括:
protected void NotifySetProperty&T&(ref T field, T value,
Expression&Func&T&& propertyExpression)
if (field == null ? value != null : !field.Equals(value))
this.NotifyPropertyChanged(propertyExpression.ToPropertyName());
因此,最后我能做这种事情:
private string _
public string Name
get { return _ }
set { this.NotifySetProperty(ref _name, value, () =& this.Name); }
它是强类型和我只提高实际更改其值的属性的事件。
解决方法 12:
这是扩展方法集中空检查之前引发事件。
public static class EventExtension
public static void RaiseEvent&T&(this EventHandler&T& handler, object obj, T args) where T : EventArgs
EventHandler&T& theHandler =
if (theHandler != null)
theHandler(obj, args);
解决方法 13:
很多时候,我已经显示一个用户友好的值,基于一个枚举值,所需,但并不想走的自定义属性的路由,,似乎不太高雅了。
使用这种方便的扩展方法:
public static string EnumValue(this MyEnum e) {
switch (e) {
case MyEnum.First:
return "First Friendly Value";
case MyEnum.Second:
return "Second Friendly Value";
case MyEnum.Third:
return "Third Friendly Value";
return "Horrible Failure!!";
我可以这样做:
Console.WriteLine(MyEnum.First.EnumValue());
解决方法 14:
要允许更多的功能组合代码:
public static Func&T, R& TryCoalesce&T, R&(this Func&T, R& f, R coalesce)
return x =&
return f(x);
public static TResult TryCoalesce&T, TResult&(this Func&T, TResult& f, T p, TResult coalesce)
return f.TryCoalesce(coalesce)(p);
然后我写出像这样的东西:
public static int ParseInt(this string str, int coalesce)
return TryCoalesce(int.Parse, str, coalesce);
解决方法 15:
我经常使用的另一套是合并的 IDictionary 方法:
public static TValue Get&TKey, TValue&(this IDictionary&TKey, TValue& d, TKey key, Func&TValue& valueThunk)
TValue v = d.Get(key);
if (v == null)
v = valueThunk();
d.Add(key, v);
public static TValue Get&TKey, TValue&(this IDictionary&TKey, TValue& d, TKey key, TValue coalesce)
return Get(d, key, () =& coalesce);
一般使用集合:
public static IEnumerable&T& AsCollection&T&(this T item)
然后为树状结构:
public static LinkedList&T& Up&T&(this T node, Func&T, T& parent)
var list = new LinkedList&T&();
node.Up(parent, n =& list.AddFirst(n));
所以我可以轻松地遍历,操作起来像一个类:
class Category
public string Name { }
public Category Parent { }
下一步,便于功能组成和更多的 F # 喜欢在 C# 中编程的方式:
public static Func&T, T& Func&T&(this Func&T, T& f)
public static Func&T1, R& Compose&T1, T2, R&(this Func&T1, T2& f, Func&T2, R& g)
return x =& g(f(x));
解决方法 16:
我喜欢 。它是一个变体的 String.Split 方法,允许使用抑制分裂时拆分字符用于实际字符串中的转义字符。
解决方法 17:
扩展方法对整型转换为解码为一枚举的枚举指定天 (每周的星期一,在这种情况下的第一天) 的位掩码:
public static IEnumerable&DayOfWeek& Days(this int dayMask)
if ((dayMask & 1) & 0) yield return DayOfWeek.M
if ((dayMask & 2) & 0) yield return DayOfWeek.T
if ((dayMask & 4) & 0) yield return DayOfWeek.W
if ((dayMask & 8) & 0) yield return DayOfWeek.T
if ((dayMask & 16) & 0) yield return DayOfWeek.F
if ((dayMask & 32) & 0) yield return DayOfWeek.S
if ((dayMask & 64) & 0) yield return DayOfWeek.S
解决方法 18:
这一具有单个元素添加在开始时创建数组:
public static T[] Prepend&T&(this T[] array, T item)
T[] result = new T[array.Length + 1];
result[0] =
Array.Copy(array, 0, result, 1, array.Length);
string[] some = new string[] { "foo", "bar" };
some = some.Prepend("baz");
与此人帮助我,当我需要一些表达式转换为它的广场:
public static double Sq(this double arg)
return arg *
(x - x0).Sq() + (y - y0).Sq() + (z - z0).Sq()
解决方法 19:
这里是另一个我所写的:
public static class StringExtensions
/// &summary&
/// Returns a Subset string starting at the specified start index and ending and the specified end
/// index.
/// &/summary&
/// &param name="s"&The string to retrieve the subset from.&/param&
/// &param name="startIndex"&The specified start index for the subset.&/param&
/// &param name="endIndex"&The specified end index for the subset.&/param&
/// &returns&A Subset string starting at the specified start index and ending and the specified end
/// index.&/returns&
public static string Subsetstring(this string s, int startIndex, int endIndex)
if (startIndex & 0) throw new ArgumentOutOfRangeException("startIndex", "Must be positive.");
if (endIndex & 0) throw new ArgumentOutOfRangeException("endIndex", "Must be positive.");
if (startIndex & endIndex) throw new ArgumentOutOfRangeException("endIndex", "Must be &= startIndex.");
return s.Substring(startIndex, (endIndex - startIndex));
/// &summary&
/// Finds the specified Start Text and the End Text in this string instance, and returns a string
/// containing all the text starting from startText, to the begining of endText. (endText is not
/// included.)
/// &/summary&
/// &param name="s"&The string to retrieve the subset from.&/param&
/// &param name="startText"&The Start Text to begin the Subset from.&/param&
/// &param name="endText"&The End Text to where the Subset goes to.&/param&
/// &param name="ignoreCase"&Whether or not to ignore case when comparing startText/endText to the string.&/param&
/// &returns&A string containing all the text starting from startText, to the begining of endText.&/returns&
public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)
if (string.IsNullOrEmpty(startText)) throw new ArgumentNullException("startText", "Must be filled.");
if (string.IsNullOrEmpty(endText)) throw new ArgumentNullException("endText", "Must be filled.");
string temp =
if (ignoreCase)
temp = s.ToUpperInvariant();
startText = startText.ToUpperInvariant();
endText = endText.ToUpperInvariant();
int start = temp.IndexOf(startText);
int end = temp.IndexOf(endText, start);
return Subsetstring(s, start, end);
这一背后的动机是简单的。它总是窃听我如何内置的子字符串的方法了 startindex 和长度作为它的参数。它总是多做 startindex 和 endindex 更有帮助。所以,我滚我自己:
使用方法:
string s = "This is a tester for my cool extension method!!";
s = s.Subsetstring("tester", "cool",true);
我不得不使用 Subsetstring 的原因是因为子字符串的重载已经采用两个整数。若任何人有更好的名字,请让我知道!!
解决方法 20:
很酷,也爱扩展 !
这里有几个。
这一将获得一个月的截止日期:
&pilerServices.Extension()& _
Public Function GetLastMonthDay(ByVal Source As DateTime) As DateTime
Dim CurrentMonth As Integer = Source.Month
Dim MonthCounter As Integer = Source.Month
Dim LastDay As DateTime
Dim DateCounter As DateTime = Source
LastDay = Source
Do While MonthCounter = CurrentMonth
DateCounter = DateCounter.AddDays(1)
MonthCounter = DateCounter.Month
If MonthCounter = CurrentMonth Then
LastDay = DateCounter
Return LastDay
End Function
这两个使反射稍微容易:
&pilerServices.Extension()& _
Public Function GetPropertyValue(Of ValueType)(ByVal Source As Object, ByVal PropertyName As String) As ValueType
Dim pInfo As System.Reflection.PropertyInfo
pInfo = Source.GetType.GetProperty(PropertyName)
If pInfo Is Nothing Then
Throw New Exception("Property " & PropertyName & " does not exists for object of type " & Source.GetType.Name)
Return pInfo.GetValue(Source, Nothing)
End Function
&pilerServices.Extension()& _
Public Function GetPropertyType(ByVal Source As Object, ByVal PropertyName As String) As Type
Dim pInfo As System.Reflection.PropertyInfo
pInfo = Source.GetType.GetProperty(PropertyName)
If pInfo Is Nothing Then
Throw New Exception("Property " & PropertyName & " does not exists for object of type " & Source.GetType.Name)
Return pInfo.PropertyType
End Function
解决方法 21:
我用最的扩展方法将不得不中的
和好的和有用的扩展到该列表中,您可以在 中找到。
解决方法 22:
有一对夫妇,我已经在这里提到使用:
if( enumVar.IsSet( MyEnum.PossibleFlag ) ) //..then
myObject.IfNotNull( x =& x.Property );
解决方法 23:
主要使用的几个扩展。第一套真是对象的扩展,只为转换。
public static class ObjectExtension
public static T As&T&(this object value)
return (value != null && value is T) ? (T)value : default(T);
public static int AsInt(this string value)
if (value.HasValue())
var success = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);
if (success)
public static Guid AsGuid(this string value)
return value.HasValue() ? new Guid(value) : Guid.E
字符串扩展
public static class StringExtension
public static bool HasValue(this string value)
return string.IsNullOrEmpty(value) ==
public static string Slug(this string value)
if (value.HasValue())
var builder = new StringBuilder();
var slug = value.Trim().ToLower();
foreach (var c in slug)
switch (c)
builder.Append("-");
builder.Append("and");
if ((c &= '0' && c &= '9') || (c &= 'a' && c &= 'z') && c != '-')
builder.Append(c);
return builder.ToString();
return string.E
public static string Truncate(this string value, int limit)
return (value.Length & limit) ? string.Concat(value.Substring(0, Math.Min(value.Length, limit)), "...") :
最后是一些枚举的扩展
public static class EnumExtensions
public static bool Has&T&(this Enum source, params T[] values)
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
foreach (var i in values)
var mask = Convert.ToInt32(i, CultureInfo.InvariantCulture);
if ((value & mask) == 0)
public static bool Has&T&(this Enum source, T values)
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
var mask = Convert.ToInt32(values, CultureInfo.InvariantCulture);
return (value & mask) != 0;
public static T Add&T&(this Enum source, T v)
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
var mask = Convert.ToInt32(v, CultureInfo.InvariantCulture);
return Enum.ToObject(typeof(T), value | mask).As&T&();
public static T Remove&T&(this Enum source, T v)
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
var mask = Convert.ToInt32(v, CultureInfo.InvariantCulture);
return Enum.ToObject(typeof(T), value & ~mask).As&T&();
public static T AsEnum&T&(this string value)
return Enum.Parse(typeof(T), value, true).As&T&();
return default(T);
解决方法 24:
这是非常简单的但这是我做很多事情,我最终目的,让扩展方法进行检查。我最喜欢的扩展方法往往是非常简单的简单的像这样,或像泰勒 L 扩展方法引发事件。
public static bool IsNullOrEmpty(this ICollection e)
return e == null || e.Count == 0;
解决方法 25:
我将大量的 Java 转换为 C#。许多方法各不相同,只在大写或其他小型的语法差异。Java 代码如
myString.toLowerCase();
将不会编译但加入扩展方法
public static void toLowerCase(this string s)
s.ToLower();
我可以捕获所有方法 (和我认为好的编译器将内联这无论如何也?)。
它当然,这项工作更轻松、 更可靠。(谢谢 @ 尤里 · - 请参阅中的答案: ) 的建议。
解决方法 26:
我从我自己的字符串架构下的个人收藏的最爱是一种将解析一个强类型的值,从任何具有 TryParse 方法的类型的字符串:
public static class StringUtils
/// &summary&
/// This method will parse a value from a string.
/// If the string is null or not the right format to parse a valid value,
/// it will return the default value provided.
/// &/summary&
public static T To&t&(this string value, T defaultValue)
where T: struct
var type = typeof(T);
if (value != null)
var parse = type.GetMethod("TryParse", new Type[] { typeof(string), type.MakeByRefType() });
var parameters = new object[] { value, default(T) };
if((bool)parse.Invoke(null, parameters))
return (T)parameters[1];
return defaultV
/// &summary&
/// This method will parse a value from a string.
/// If the string is null or not the right format to parse a valid value,
/// it will return the default value for the type.
/// &/summary&
public static T To&t&(this string value)
where T : struct
return value.To&t&(default(T));
它非常适合从查询字符串中获取强类型的信息:
var value = Request.QueryString["value"].To&int&();
解决方法 27:
我讨厌做这个世界各地:
DataSet ds = dataLayer.GetSomeData(1, 2, 3);
if(ds != null){
if(ds.Tables.Count & 0){
DataTable dt = ds.Tables[0];
foreach(DataRow dr in dt.Rows){
//Do some processing
而通常使用以下的扩展方法:
public static IEnumerable&DataRow& DataRows(this DataSet current){
if(current != null){
if(current.Tables.Count & 0){
DataTable dt = current.Tables[0];
foreach(DataRow dr in dt.Rows){
因此,然后成为第一个示例:
foreach(DataRow row in ds.DataRows()){
//Do some processing
耶,扩展方法 !
解决方法 28:
String.format 不应是静态。所以,我用称为 frmt 扩展方法:
&Extension()& Public Function frmt(ByVal format As String,
ByVal ParamArray args() As Object) As String
If format Is Nothing Then Throw New ArgumentNullException("format")
Return String.Format(format, args)
End Function
当我想要读取或写入的字节流无施工 (技术上你不该把修改原始流后你已经包覆的作者) 的二进制编写器的数量:
&Extension()& Public Function Bytes(ByVal n As ULong,
ByVal byteOrder As ByteOrder,
Optional ByVal size As Integer = 8) As Byte()
Dim data As New List(Of Byte)
Do Until data.Count &= size
data.Add(CByte(n And CULng(&HFF)))
Select Case byteOrder
Case ByteOrder.BigEndian
Return data.ToArray.reversed
Case ByteOrder.LittleEndian
Return data.ToArray
Throw New ArgumentException("Unrecognized byte order.")
End Select
End Function
&Extension()& Public Function ToULong(ByVal data As IEnumerable(Of Byte),
ByVal byteOrder As ByteOrder) As ULong
If data Is Nothing Then Throw New ArgumentNullException("data")
Dim val As ULong
Select Case byteOrder
Case ByteOrder.LittleEndian
data = data.Reverse
Case ByteOrder.BigEndian
'no change required
Throw New ArgumentException("Unrecognized byte order.")
End Select
For Each b In data
val = val Or b
Return val
End Function
解决方法 29:
这一转移的序列,以便您获取给定的项第一。我用它,例如移动它,以便在序列中的第一天是当前区域性为一周的第一天,一天的周。
/// &summary&
/// Shifts a sequence so that the given &paramref name="item"/& becomes the first.
/// Uses the specified equality &paramref name="comparer"/& to find the item.
/// &/summary&
/// &typeparam name="TSource"&Type of elements in &paramref name="source"/&.&/typeparam&
/// &param name="source"&Sequence of elements.&/param&
/// &param name="item"&Item which will become the first.&/param&
/// &param name="comparer"&Used to find the first item.&/param&
/// &returns&A shifted sequence. For example Shift({1,2,3,4,5,6}, 3) would become {3,4,5,6,1,2}. &/returns&
public static IEnumerable&TSource& Shift&TSource&(this IEnumerable&TSource& source, TSource item, IEqualityComparer&TSource& comparer)
var queue = new Queue&TSource&();
bool found =
foreach (TSource e in source)
if (!found && comparer.Equals(item, e))
if (found)
queue.Enqueue(e);
while (queue.Count & 0)
yield return queue.Dequeue();
/// &summary&
/// Shifts a sequence so that the given item becomes the first.
/// Uses the default equality comparer to find the item.
/// &/summary&
/// &typeparam name="TSource"&Type of elements in &paramref name="source"/&.&/typeparam&
/// &param name="source"&Sequence of elements.&/param&
/// &param name="element"&Element which will become the first.&/param&
/// &returns&A shifted sequence. For example Shift({1,2,3,4,5,6}, 3) would become {3,4,5,6,1,2}. &/returns&
public static IEnumerable&TSource& Shift&TSource&(this IEnumerable&TSource& source, TSource element)
return Shift(source, element, EqualityComparer&TSource&.Default);
解决方法 30:
我在 MVC 项目 class-name-to-upper-case-url 解决以下的自动驾驶仪:
public static class RouteCollectionExt
public static Route MapRouteLowercase(this RouteCollection routes, string name, string url, object defaults)
var route = new LowercaseRoute(url, new RouteValueDictionary(defaults), new MvcRouteHandler());
routes.Add(name, route);
private class LowercaseRoute : Route
public LowercaseRoute(string url, IRouteHandler routeHandler)
: base(url, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
: base(url, defaults, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
: base(url, defaults, constraints, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler)
: base(url, defaults, constraints, dataTokens, routeHandler) { }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
var path = base.GetVirtualPath(requestContext, values);
if (path != null)
path.VirtualPath = path.VirtualPath.ToLowerInvariant();
使用方法:
routes.MapRouteLowercase(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }}

我要回帖

更多关于 轻度甲亢会自愈吗 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信