小弟之前在用string.Format("Hello {0}. Hi {1}.", "puma", "hent");
在想說為什麼參數可以動態增加,去找了一下資料,才發現C#有一個params的關鍵字
利用這個params關鍵字就可以模擬跟string.Format()一樣的做法了
小弟之前在用string.Format("Hello {0}. Hi {1}.", "puma", "hent");
在想說為什麼參數可以動態增加,去找了一下資料,才發現C#有一個params的關鍵字
利用這個params關鍵字就可以模擬跟string.Format()一樣的做法了
TestMultiParam.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestMultiParam.aspx.cs" Inherits="Modules_News_test_TestMultiParam" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>TestMultiParam</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>TestMultiParam</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
TestMultiParam.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class Modules_News_test_TestMultiParam : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string內建的Format方法
Response.Write(string.Format("Hello {0}. Now Time: {1}. ", "puma", DateTime.Now.ToString("hh:mm:ss")));
Response.Write("<br/><br/>");
//做一個跟string.Format一樣的方法
Response.Write(FormatWith("Hello {0}. Now Time: {1}. ", "hent", DateTime.Now.ToString("hh:mm:ss")));
}
//使用params,模擬string.Format的用法
public string FormatWith(string format, params object[] args)
{
for (int i = 0; i < args.Length; i++)
{
format = format.Replace("{" + i + "}", args[i].ToString());
}
return format;
}
}
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class Modules_News_test_TestMultiParam : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string內建的Format方法
Response.Write(string.Format("Hello {0}. Now Time: {1}. ", "puma", DateTime.Now.ToString("hh:mm:ss")));
Response.Write("<br/><br/>");
//做一個跟string.Format一樣的方法
Response.Write(FormatWith("Hello {0}. Now Time: {1}. ", "hent", DateTime.Now.ToString("hh:mm:ss")));
}
//使用params,模擬string.Format的用法
public string FormatWith(string format, params object[] args)
{
for (int i = 0; i < args.Length; i++)
{
format = format.Replace("{" + i + "}", args[i].ToString());
}
return format;
}
}
執行結果:
參考網址:http://msdn2.microsoft.com/zh-tw/library/w5zay9db(VS.80).aspx