Tricks with delegates

Origin:http://www.dotnet2themax.com/blogs/fbalena/PermaLink,guid,b2a8f5e9-ddf1-45eb-ad8e-78c88c13ab2f.aspx

 

Consider the following code, that converts all the elements of an Int32 array into the corresponding hex value:

 

' VB
Dim intArray() As Integer = {4, 6, 9, 10, 99, 233, 34, 88, 189}
Dim hexArray(intArray.Length - 1) As String
For i As Integer = 0 To intArray.Length - 1
   hexArray(i) = intArray(i).ToString(
"X" )
Next

 

// C#
int [] intArray = {4, 6, 9, 10, 99, 233, 34, 88, 189};
string [] hexArray = new string [intArray.Length];
for ( int i = 0; i < intArray.Length; i++)
{
   hexArray[i] = intArray[i].ToString(
"X" );
}

The question is: how can you make this code more concise in .NET 2.0? The first answer that might come up is to use the Array.ConvertAll method together with a C#'s anonymous method:

 

string [] hexArray = Array .ConvertAll< int , string >(intArray, new Converter < int , string >(
  
delegate ( int n) { return n.ToString( "X" );}));

Actually, you can write even more concise code if you remember than the Microsoft.VisualBasic library already contains the Hex method, which matches the signature of the Converter<int,string> delegate. Using this method and delegate inference, you can shrink the code to:

 

' VB
Dim hexArray() As String = Array.ConvertAll( Of Integer , String )(intArray, AddressOf Hex)
// C#
string [] hexArray = Array .ConvertAll< int , string >(intArray, Microsoft.VisualBasic. Conversion .Hex );

I am certain that few C# developers will use this trick, but I thought it was worth mentioning. (Of course, you must add a reference to the Microsoft.VisualBasic.dll assembly if you work with C#.) The key idea, however, is that in some cases you don't need to write an anonymous method to accomplish a given task, because often you can find what you're looking for in the .NET Framework. For example, you can display all the elements of an array in the Console window with just one statement:

 

' VB
Array.ForEach(hexArray, AddressOf Console.WriteLine)
// C#
Array.ForEach(hexArray, Console.WriteLine);

There are many other methods in the VB library that you can use to convert all the elements of an array or a generic List, including UCase, LCase, LTrim, RTrim, and Trim.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值