摘要:(200-07-21) LINQ Extend Method (擴充方法) #1
(擴充方法)Extend Method
1.建立 類別_擴充方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace linqwin
{
//將類別設定為static
public static class MyExtensionString
{
//共用static
public static Int32 doubleValue(this String str) // <==咬住
{
//先剖析是否可以轉換成整數
try
{
Int32 r = Int32.Parse(str);
return r * r;
}
catch (Exception ex)
{
throw ex;
}
}
}
}2.使用擴充方法
String str1 = "12";
//咬擴充功能(Method)
Int32 r = str1.doubleValue();
MessageBox.Show(r.ToString());(靜態方法)static Method : 晚期繫結直接載入全域記憶體位置
1.建立 類別_靜態方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace linqwin
{
public class MyString
{
//共用static
public static Int32 doubleValue(String str)
{
//先剖析是否可以轉換成整數
try
{
Int32 r = Int32.Parse(str);
return r * r;
}
catch (Exception ex)
{
throw ex;
}
}
}
}2.使用靜態方法
//字串
String s1 = "5";
//呼叫類別成員
Int32 r=MyString.doubleValue(s1);
MessageBox.Show(r.ToString());
課程補充
字串集區觀念
//建構字串物件
//字串在new時會新產一個物件,不使用集區觀念
String str1 = new String(new char[] { 'e', 'r', 'i', 'c' });
String str2 = new String(new char[] { 'e', 'r', 'i', 'c' });
//str3 與 str4 是集區觀念 省記憶體空間
String str3 = "Eric";
String str4 = "Eric";
//物件化的method
str4=str4.ToLower();
MessageBox.Show(String.Format("str3:{0} str4:{1}", str3, str4));