Summary of Common Application Function Examples of C

  • 2021-11-30 01:15:19
  • OfStack

This paper summarizes the common application functions of C # with examples. Share it for your reference, as follows:

1. Write CS code on the page (code embedded)


<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Collections.Generic" %>
<Script runat="server">
  public int userId = 0;
  protected void Page_Load(object sender, EventArgs e)
  {
    userId =Convert.ToInt32(Request.QueryString["UserID"]);
    Response.Write(userId);
  }
</Script>
<%
  if (userId > 0){
    msg = " Welcome to login !";
  }
  else {
    msg = " User not found ";
  }
%>
<%= this.msg %>

2. Get the time interval


/// <summary>
///  Get the time interval (simulate the time interval when Weibo publishes articles) 
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public string GetDateStr(DateTime date)
{
  if (date < DateTime.Now)
  {
    TimeSpan ts = DateTime.Now - date;
    if (ts.TotalHours < 1 && ts.TotalMinutes < 1)
    {
      return "1 Minutes ago ";
    }
    else if (ts.TotalHours < 1 && ts.TotalMinutes > 0)
    {
      return Convert.ToInt32(ts.TotalMinutes) + " Minutes ago ";
    }
    else if (ts.TotalHours < 4)
    {
      return Convert.ToInt32(ts.TotalHours) + " Hours ago ";
    }
    else if (DateTime.Now.Date == date.Date)
    {
      return date.ToString("HH:mm");
    }
    else
    {
      return date.ToString("yyyy-MM-dd");
    }
  }
  return date.ToString("yyyy-MM-dd");
}

3. Traverse the parameter list in Url


/// <summary>
///  Traversal Url List of parameters in 
/// </summary>
/// <returns> Such as :(?userId=43&userType=2)</returns>
public string GetUrlParam()
{
  string urlParam = "";
  if (Request.QueryString.Count > 0)
  {
    urlParam = "?";
    NameValueCollection keyVals = Request.QueryString;
    foreach (string key in keyVals.Keys)
    {
      urlParam += key + "=" + keyVals[key] + "&";
    }
    urlParam = urlParam.Substring(0, urlParam.LastIndexOf('&'));
  }
  return urlParam;
}

4. Clear the text HTML code


using System.Text.RegularExpressions;
/// <summary>
///  Clear text HTML Code 
/// </summary>
public string RemoveHtmlTag(string htmlStr)
{
  if (string.IsNullOrEmpty(htmlStr))
    return string.Empty;
  return Regex.Replace(htmlStr, @"<[^>]*>", "");
}

5. Reflection Creates Class Instances by Class Name


using System.Reflection;
/// <summary>
///  Reflex   Create a class instance by class name 
/// </summary>
public void ReflecTest()
{
  Object objClass = Assembly.GetExecutingAssembly().CreateInstance("MyStudy.BLL.BookInfoBLL"); // Parameter: The fully qualified name of the class, without the suffix name of the class 
  if (objClass != null)
  {
    BookInfoBLL bll = (BookInfoBLL)objClass;
  }
}

6. Currency type conversion


/// <summary>
///  Currency 
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToMoney(object obj)
{
  return String.Format("{0:C}", obj);
}

7. Decimal places


//1. Number of decimal points 
string str1 = String.Format("{0:F1}", 56789); //result: 56789.0
string str2 = String.Format("{0:F2}", 56789); //result: 56789.00
string str3 = String.Format("{0:N1}", 56789); //result: 56,789.0
string str4 = String.Format("{0:N2}", 56789); //result: 56,789.00
string str5 = String.Format("{0:N3}", 56789); //result: 56,789.000
string str6 = (56789 / 100.0).ToString("#.##"); //result: 567.89
string str7 = (56789 / 100).ToString("#.##"); //result: 567
//2. Reservation N Bit ,4 Shed 5 Into  .
decimal d= decimal.Round(decimal.Parse("0.55555"),2);
//3. Reservation N Bit 4 Shed 5 Into 
Math.Round(0.55555, 2);

8. Use TryGetValue to improve the performance of obtaining dictionary values

When using TryGetValue, the performance is doubled compared with ContainsKey when taking a large number of values.


Dictionary<int, String> dic = new Dictionary<int, String>();
dic.Add(1," Zhang 3");
dic.Add(2," Li 4");
string name = "";
// Wrong writing, low efficiency 
if (dic.ContainsKey(1))
{
  name = dic[1];
  Console.WriteLine(name);
}
// Correct writing and improved efficiency 1 Times 
if (dic.TryGetValue(1, out name))
{
  Console.WriteLine(name);
}

For more readers interested in C # related content, please check out the topics on this site: "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"

I hope this article is helpful to everyone's C # programming.


Related articles: