C#扩展方法试用

以前某面试题要求给string扩展一个IsNotNullOrEmpty的方法。当时没有想到合适的办法。后来发现3.0以后加了个扩展方法的语法糖。现收集了几位园友的某些实际应用,自己也试试写了几个方法。大家用的着的,尽管Copy啊。  如果你觉得代码很熟悉,是你写的我在此谢过了。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinComman;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            //简写 foreach测试
            string[] temp = new string[] {"White","Red","Green"};
            temp.Each(str => Console.WriteLine(str));

            IList<Employee> empList = new List<Employee> { 
                new Employee{EmpNo="001",Name="小李"},
                new Employee{EmpNo="002",Name="小赵"},
                new Employee{EmpNo="003",Name="小王"}
            };
            //获取某个List的每个Item的某个属性,返回为一个数组
            empList.ToStringArray("Name").Each(str => Console.WriteLine(str));

            Console.WriteLine(DateTime.Now.TruncateTime().ToString());
            decimal amount = 9810298.36M;
            Console.WriteLine(amount.ToRMB());           
        }
    }

    public class Employee
    {
        public string EmpNo
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WinComman
{
///<summary>
/// C#扩展类
///</summary>
public static class GhoughShawExtClass
{
///<summary>
/// 按指定属性返回T的指定属性ToString()后的数组
///</summary>
///<typeparam name="T"></typeparam>
///<param name="list">集合</param>
///<param name="propertyName">属性,需要完全匹配大小写</param>
///<returns></returns>
public static string[] ToStringArray<T>(this IEnumerable<T> list, string propertyName)
{
string[] result = new string[list.Count()];
int i = 0;
foreach (var item in list)
{
Type t = item.GetType();
var piList = t.GetProperties();
var pi = piList.Where(p => p.Name.Equals(propertyName)).FirstOrDefault();
if (pi != null)
{
result[i] = pi.GetValue(item, null).ToString();
i++;
}
else
{
break;
throw new Exception(string.Format("对象'{0}',不存在'{1}'属性!", t.Name, propertyName));
};

}
return result;
}


///<summary>
/// 日期时间型取整,舍去时间
///</summary>
///<param name="value"></param>
///<returns></returns>
public static DateTime TruncateTime(this DateTime value)
{
return DateTime.Parse(value.ToLongDateString() + " 00:00:00");
}

///<summary>
/// 货币转人民币大写
///</summary>
///<param name="amountValue"></param>
///<returns></returns>
public static string ToRMB(this decimal amountValue)
{
var money = new Money(amountValue);
return money.ToString();
}

///<summary>
/// 货币转人民币大写
///</summary>
///<param name="amountValue"></param>
///<returns></returns>
public static string ToRMB(this double amountValue)
{
var money = new Money(Convert.ToDecimal(amountValue));
return money.ToString();
}

#region 简化流程型语句 如Foreach For 非本人代码,取自博客园某牛人(忘记了,不好意思),在此谢过

///<summary>
/// 简化Foreach的写法
///</summary>
///<typeparam name="TSource"></typeparam>
///<param name="obj"></param>
public delegate void EachMethod<TSource>(TSource obj);
public static void Each<TSource>(this IEnumerable<TSource> source, EachMethod<TSource> method)
{
foreach (TSource obj in source)
{
method(obj);
}
}

///<summary>
/// 简化在循环内部,Item满足某个条件时,执行某个方法的写法
///</summary>
///<typeparam name="TSource"></typeparam>
///<param name="source"></param>
///<param name="selector"></param>
///<param name="method"></param>
public static void If<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> selector, EachMethod<TSource> method)
{
foreach (TSource obj in source)
{
if (selector(obj))
method(obj);
}
}

///<summary>
/// 简化For的写法
///</summary>
///<param name="max"></param>
///<param name="method"></param>
public static void For(this int max, Func<int, bool> method)
{
for (int i = 0; i < max; i++)
{
if (!method(i))
{
break;
}
}
}

///<summary>
/// 简化For的写法 Down To
///</summary>
///<param name="max"></param>
///<param name="method"></param>
public static void DownFor(this int max, int min, Func<int, bool> method)
{
for (int i = max; i > min; i--)
{
if (!method(i))
{
break;
}
}
}
#endregion
}

///<summary>
/// dudu 写的Wcf Client 扩展类,这个办法我试用过了。果然是享受
///</summary>
public class WcfClient
{
public static TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> func)
{
var chanFactory = new ChannelFactory<TChannel>("*");
TChannel channel = chanFactory.CreateChannel();
TReturn result = func(channel);
try
{
((IClientChannel)channel).Close();
}
catch
{
((IClientChannel)channel).Abort();
}
return result;
}
}

///<summary>
/// 伍华聪的WCF client 扩展
///</summary>
public static class WcfExtensions
{
public static void Using<T>(this T client, Action<T> work) where T : ICommunicationObject
{
try
{
work(client);
client.Close();
}
catch (CommunicationException ex)
{
client.Abort();
}
catch (TimeoutException ex)
{
client.Abort();
}
catch (Exception ex)
{
client.Abort();
}
}
}

public class Money
{
public string Yuan = ""; // “元”,可以改为“圆”、“卢布”之类
public string Jiao = ""; // “角”,可以改为“拾”
public string Fen = ""; // “分”,可以改为“美分”之类
static string Digit = "零壹贰叁肆伍陆柒捌玖"; // 大写数字
bool isAllZero = true; // 片段内是否全零
bool isPreZero = true; // 低一位数字是否是零
bool Overflow = false; // 溢出标志
long money100; // 金额*100,即以“分”为单位的金额
long value; // money100的绝对值
StringBuilder sb = new StringBuilder(); // 大写金额字符串,逆序
// 只读属性: "零元"
public string ZeroString
{
get { return Digit[0] + Yuan; }
}
// 构造函数
public Money(decimal money)
{
try { money100 = (long)(money * 100m); }
catch { Overflow = true; }
if (money100 == long.MinValue) Overflow = true;
}
// 重载 ToString() 方法,返回大写金额字符串
public override string ToString()
{
if (Overflow) return "金额超出范围";
if (money100 == 0) return ZeroString;
string[] Unit = { Yuan, "", "亿", "", "亿亿" };
value = System.Math.Abs(money100);
ParseSection(true);
for (int i = 0; i < Unit.Length && value > 0; i++)
{
if (isPreZero && !isAllZero) sb.Append(Digit[0]);
if (i == 4 && sb.ToString().EndsWith(Unit[2]))
sb.Remove(sb.Length - Unit[2].Length, Unit[2].Length);
sb.Append(Unit[i]);
ParseSection(false);
if ((i % 2) == 1 && isAllZero)
sb.Remove(sb.Length - Unit[i].Length, Unit[i].Length);
}
if (money100 < 0) sb.Append("");
return Reverse();
}
// 解析“片段”: “角分(2位)”或“万以内的一段(4位)”
void ParseSection(bool isJiaoFen)
{
string[] Unit = isJiaoFen ?
new string[] { Fen, Jiao } :
new string[] { "", "", "", "" };
isAllZero = true;
for (int i = 0; i < Unit.Length && value > 0; i++)
{
int d = (int)(value % 10);
if (d != 0)
{
if (isPreZero && !isAllZero) sb.Append(Digit[0]);
sb.AppendFormat("{0}{1}", Unit[i], Digit[d]);
isAllZero = false;
}
isPreZero = (d == 0);
value /= 10;
}
}
// 反转字符串
string Reverse()
{
StringBuilder sbReversed = new StringBuilder();
for (int i = sb.Length - 1; i >= 0; i--)
sbReversed.Append(sb[i]);
return sbReversed.ToString();
}
}
}

 

 

posted @ 2011-11-07 13:48  数据酷软件  阅读(1260)  评论(1编辑  收藏  举报