我已经写了无数个扩展方法,以下是我发现特别有用的一些。欢迎自由实现。
public static class ControlExtenders
{
public static T FindControl<T>(this Control control, string id) where T : Control
{
Control _control = control.FindControl(id);
if (_control != null && _control is T)
{
return (T)_control;
}
_control = (T)Activator.CreateInstance(typeof(T));
if (!(_control is ExtenderControlBase))
{
_control.Visible = false;
}
_control.ID = id;
control.Controls.Add(_control);
return (T)_control;
}
}
public static class GenericListExtenders
{
public static void SortObjects<T>(this List<T> list, string fieldName, SortDirection sortDirection)
{
PropertyInfo propInfo = typeof(T).GetProperty(fieldName);
if (propInfo != null)
{
Comparison<T> compare = delegate(T a, T b)
{
bool asc = sortDirection == SortDirection.Ascending;
object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);
object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);
return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;
};
list.Sort(compare);
}
}
public static List<T> Page<T>(this List<T> list, string sortField, bool sortDirection, int from, int to, bool copy)
{
List<T> _pageList = new List<T>();
if (copy)
{
T[] _arrList = new T[list.Count];
list.CopyTo(_arrList);
_pageList = new List<T>(_arrList);
}
else
{
_pageList = list;
}
if (from > _pageList.Count)
{
int diff = Math.Abs(from - to);
from = _pageList.Count - diff;
}
if (to > _pageList.Count)
{
to = _pageList.Count;
}
if (!string.IsNullOrEmpty(sortField))
{
SortDirection sortDir = SortDirection.Descending;
if (!sortDirection) sortDir = SortDirection.Ascending;
_pageList.SortObjects(sortField, sortDir);
}
int count = to - from;
if (from + count > _pageList.Count) count -= (from + count) - _pageList.Count;
T[] pagged = new T[count];
_pageList.CopyTo(from, pagged, 0, count);
return new List<T>(pagged);
}
public static void Shuffle<T>(this List<T> list)
{
Random rng = new Random();
for (int i = list.Count - 1; i > 0; i--)
{
int swapIndex = rng.Next(i + 1);
if (swapIndex != i)
{
T tmp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = tmp;
}
}
}
public static DataTable ToDataTable<T>(this List<T> list, string[] columns)
{
List<string> _columns = new List<string>(columns);
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
if (_columns.Contains(info.Name) || columns == null)
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
if (_columns.Contains(info.Name) || columns == null)
{
row[info.Name] = info.GetValue(t, null);
}
}
dt.Rows.Add(row);
}
return dt;
}
}
public static class DateTimeExtenders
{
public static int MonthToNumber(this DateTime datetime, string month)
{
month = month.ToLower();
for (int i = 1; i <= 12; i++)
{
DateTime _dt = DateTime.Parse("1." + i + ".2000");
string _month = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i).ToLower();
if (_month == month)
{
return i;
}
}
return 0;
}
public static string MonthToName(this DateTime datetime, int month)
{
for (int i = 1; i <= 12; i++)
{
if (i == month)
{
return CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i);
}
}
return "";
}
}
public static class ObjectExtender
{
public static object CloneBinary<T>(this T originalObject)
{
using (var stream = new System.IO.MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, originalObject);
stream.Position = 0;
return (T)binaryFormatter.Deserialize(stream);
}
}
public static object CloneObject(this object obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, obj);
memStream.Position = 0;
return binaryFormatter.Deserialize(memStream);
}
}
}
public static class StringExtenders
{
public static Unit ToUnit(this string value)
{
if (string.IsNullOrEmpty(value))
return Unit.Empty;
value = value.Trim();
if (value.EndsWith("px"))
{
string _int = value.Replace("px", "");
double _val = 0;
if (!double.TryParse(_int, out _val))
{
return Unit.Empty;
}
return new Unit(_val, UnitType.Pixel);
}
if (value.EndsWith("%"))
{
string _int = value.Replace("%", "");
double _val = 0;
if (!double.TryParse(_int, out _val))
{
return Unit.Empty;
}
return new Unit(_val, UnitType.Percentage);
}
return new Unit();
}
public static string Alternative(this string str, string alternative)
{
if (string.IsNullOrEmpty(str)) return alternative;
return str;
}
public static string StripHTML(this string html)
{
string nohtml = Regex.Replace(html, "<(.|\n)*?>", "");
nohtml = nohtml.Replace("\r\n", "").Replace("\n", "").Replace(" ", "").Trim();
return nohtml;
}
}
第一个是我最喜欢的,因为它使我能够替换:
Control c = this.FindControl("tbName");
if (c != null)
{
customer.Name = ((TextBox)c).Text;
}
使用这个:
TextBox c = this.FindControl<TextBox>("tbName");
customer.Name = c.Text;
设置默认字符串值:
string str = "";
if (string.IsNullOrEmpty(str))
{
str = "I'm empty!";
}
Becomes:
str = str.Alternative("I'm empty!")