C# 使用高级编程技术创建线性列表

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace MyOwnGeneric
{
    class OwnObject<T>
    {
        private T content;
        private OwnObject<T> next;

        public T Content
        {
            get { return content; }
            set { content = value; }
        }

        public OwnObject<T> Next
        {
            get { return next; }
            set { next = value; }
        }

        public override string ToString()
        {
            return content.ToString();
        }
    }

    class LinList<T> : IEnumerable<T>
    {
        private OwnObject<T> first;
        private OwnObject<T> last;

        public OwnObject<T> First
        {
            get { return first; }
            set { first = value; }
        }

        public OwnObject<T> Last
        {
            get { return last; }
            set { last = value; }
        }

        public void Add(OwnObject<T> item)
        {
            if (first == null)
            {
                first = item;
                last = item;
            }
            else
            {
                last.Next = item;
                last = item;
            }
        }

        //function to count items in LinList
        public int Count()
        {
            int counter = 0;
            OwnObject<T> position = first;
            while (position != null)
            {
                counter++;
                position = position.Next;
            }
            return counter;
        }

        //function to get the content at a fix position in LinList
        public T GetItem(int pos)
        {
            int counter = 0;
            OwnObject<T> position = first;
            //T result = null not possible because value type
            T result = default(T);
            while (position != null)
            { 
                if (counter == pos)
                {
                    result = position.Content;
                    break;
                }
                counter++;
                position = position.Next;
            }
            return result;
        }

        public override string ToString()
        {
            string result = "";
            OwnObject<T> position = first;
            while (position != null)
            {
                result += position.ToString();
                if (position.Next != null)
                    result += " - ";
                position = position.Next;
            }
            return result;
        }

        //indexer
        public T this[int index]
        {
            get
            {
                return this.GetItem(index);
            }
        }

        //interface IEnumerable
        public IEnumerator<T> GetEnumerator()
        {
            OwnObject<T> position = first;
            while (position != null)
            {
                yield return position.Content;
                position = position.Next;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            LinList<string> test = new LinList<string>();
            OwnObject<string> testcont = new OwnObject<string>();
            testcont.Content = "test";
            OwnObject<string> testcont2 = new OwnObject<string>();
            testcont2.Content = "test2";
            OwnObject<string> testcont3 = new OwnObject<string>();
            testcont3.Content = "test3";

            test.Add(testcont);
            test.Add(testcont2);
            test.Add(testcont3);

            //using the interface of IEnumerable
            foreach (string item in test)
            {
                Console.WriteLine(item);
            }

            //using the indexer and the item counter
            for (int i = 0; i < test.Count(); i++)
            {
                Console.WriteLine(test[i]);
            }
        }
    }
}

C# 方法和不同类型的参数传递

using System;

namespace parameters
{
    public static class democlass
    {
        //normal use
        public static int Add(int left, int right)
        {
            return left + right;
        }

        //use the ref Parameter, e.g. for increment
        public static void AddPlus(ref int number)
        {
            number = number + 1;
        }

        //use the out Parameter
        public static void GetHundred(out int number)
        {
            number = 100;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;
            int c;

            c = democlass.Add(a, b);
            Console.WriteLine(c);           //30

            democlass.AddPlus(ref c);
            Console.WriteLine(c);           //31

            democlass.GetHundred(out c);
            Console.WriteLine(c);           //100
        }
    }
}

C# 包括Tag C Sharp XML文档评论

// compile with: /doc:DocFileName.xml 

/// <include file='xml_include_tag.doc' path='MyDocs/MyMembers[@name="test"]/*' />
class Test
{
    static void Main()
    {
    }
}

/// <include file='xml_include_tag.doc' path='MyDocs/MyMembers[@name="test2"]/*' />
class Test2
{
    public void Test()
    {
    }
}

C# 将无效替换为有效的文件名

static string removeBadChar(string filename)
        {
            // Replace invalid characters with "_" char.
            return Regex.Replace(filename, @"[^\w\.-]", "_");

        }

C# 列表标签C Sharp XML文档评论

<list type="bullet" | "number" | "table">
    <listheader>
        <term>term</term>
        <description>description</description>
    </listheader>
    <item>
        <term>term</term>
        <description>description</description>
    </item>
</list>

C# paramref Tag C Sharp XML文档评论

/// text for class TestClass
public class TestClass
{
    /// <summary>DoWork is a method in the TestClass class.  
    /// The <paramref name="Int1"/> parameter takes a number.
    /// </summary>
    public static void DoWork(int Int1)
    {
    }

    /// text for Main
    static void Main()
    {
    }
}

C# 示例C#代码新增

public void testClipBoardContentsAreChangedWhenQueueIsEmptyContentProvided() {
        assertTrue(queue.isClipBoardContentsChanged("New Content"));
    }

C# XmlDocument流畅的界面

XmlDocument fluent interface

C# 有趣的是C#和HP Laserjet

namespace hphack
{
  using System;
  using System.Text;
  using System.Net;
  using System.Net.Sockets;

  public class PrnHack
  {
    public static int Main(string[] args)
    {
      if(!ParseArgs(args))
      {
        return -1;
      }
            
      Console.WriteLine("\nHP Display Hack");
      Console.WriteLine("Host: {0}", args[0]);
      Console.WriteLine("Message: {0}\n", message);
            
      IPEndPoint ipEndPoint;
      ipEndPoint = new IPEndPoint( Dns.Resolve(args[0]).AddressList[0], PJL_PORT);

      Console.WriteLine("Host is {0}", ipEndPoint.ToString());

      Socket socket;
      socket = new Socket(
                        AddressFamily.InterNetwork,  
                        SocketType.Stream, 
                        ProtocolType.Tcp
                     );

      socket.Connect(ipEndPoint);

      byte [] sendData;
      string sendString;

      sendString = String.Format(
                "\x1B%-12345X@PJL RDYMSG DISPLAY = \"{0}\"
\x1B%-12345X
", 
                message
           );

      sendData = Encoding.ASCII.GetBytes(sendString);
                
      int result;
      result = socket.Send(sendData, sendData.Length, 0);

      if(result == 0)
      {
        Console.WriteLine("Could not send on socket");
      }
        
      socket.Close();
        
      Console.WriteLine("Finished\n\n");
      return 0;
    }

 

    protected static bool ParseArgs(string[] args)
    {
      if(args.Length != 2)
      {
        Console.WriteLine(
                  "HP Display Hack: " + 
                  "hphack printername \"message\" "
            );
        return false;
      }

      if(args[1].Length > 16)
      {
        Console.WriteLine("Message must be <= 16 characters");
        return false;
      }
        
      if(args[1].CompareTo("random") == 0)
      {
        message = GetRandomMessage();
      }
      else
      {
        message = args[1];
      }

      return true;
    }


    public static string GetRandomMessage()
    {
      string [] Messages = { 
                             "BUZZ OFF", 
                             "TOUCH ME",
                             "STEP AWAY",
                             "SET TO STUN",
                             "SCORE = 3413",
                             "PAT EATS MICE",
                             "FEED ME",
                             "GO AWAY",
                             "NEED MORE SPACE",
                             "POUR ME A DRINK",
                             "IN DISTRESS",
                             "NICE SHIRT",
                             "GO AWAY",
                             "NO PRINT FOR YOU",
                             "RADIATION LEAK",
                             "HANDS UP",
                             "PRESS MY BUTTON",
                             "TAKE ME HOME",
                             "LOOKS LIKE RAIN",
                             "HELLO WORLD",
                             "NICE HAIR",
                             "NEED A MINT?",
                             "BE GENTLE",
                             "BE KIND",
                             "INSERT DISK",
                             "BUY ME LUNCH",
                             "DONT STOP",
                             "COME CLOSER",
                             "TAKE A BREAK",
                             "INSERT QUARTER",
                             "BLACK SABBATH"
      };


      Random r = new Random();
      return Messages[r.Next() % Messages.Length];
    }

    protected const int PJL_PORT = 9100;
    protected static string message = "NO MESSAGE";
        
  }
}

C# 数据访问

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Configuration;

DataAddUpdateDelete.Data_Insert(Convert.ToInt32(strGrantXMLID),
	strGrantName,
	strOrganization,
	dtYear,
	dAmount,
	intDuration,
	strPrimaryNTEE,
	strSpecificNTEE,
	strAddress1 + " " + strAddress2,
	strCity,
	strState,
	strZipCode,
	strPhone,
	"0",
	System.DateTime.Now,
	"0",
	System.DateTime.Now);
							
							
namespace DataAccess
{
    public static class DataSelection
    {

        /// <summary>
        /// Executes a stored procedure anda returns a datatable
        /// </summary>
        /// <param name="sp">This must be a stored procedure</param>
        /// <returns>Data Table</returns>
        public static DataTable ReturnDataTable(string sp)
        {
            return ReturnDataTable(sp, null);
        }

        /// <summary>
        /// Executes a stored procedure anda returns a datatable
        /// </summary>
        /// <param name="sp">This must be a stored procedure</param>
        /// <param name="Parameters">parameters to pass to stored procedure</param>
        /// <returns>Data Table</returns>
        public static DataTable ReturnDataTable(string sp, ListDictionary Parameters)
        {
            SqlConnection cnDBConn = new SqlConnection(ConfigurationSettings.AppSettings["DBConn"]);
            SqlCommand cmdSPCommand = new SqlCommand();

            try
            {
                cnDBConn.Open();
                cmdSPCommand.Connection = cnDBConn;

                cmdSPCommand.CommandText = sp;
                cmdSPCommand.CommandType = CommandType.StoredProcedure;
                IDataParameter p;

                if (Parameters != null)
                {
                    foreach (System.Collections.DictionaryEntry param in Parameters)
                    {
                        p = param.Key as IDataParameter;

                        if (null == p)
                        {
                            p.ParameterName = (string)param.Key;
                            p.Value = param.Value;
                        }
                        else
                        {
                            p.Value = param.Value;
                        }

                        cmdSPCommand.Parameters.Add(p);
                    }
                }
                SqlDataAdapter daAdapter = new SqlDataAdapter(cmdSPCommand);

                DataTable dt = new DataTable();
                daAdapter.Fill(dt);

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cnDBConn.State == ConnectionState.Open)
                    cnDBConn.Close();
            }

        }
    }


    /// <summary>
    /// This class contains all insert stored procedures
    /// </summary>
    public static class DataAddUpdateDelete
    {
	
        public static void Data_Insert(int GrantID, 
            string Grant_Name,
            string Organization,
            DateTime Year,
            decimal Amount,
            int Duration,
            string Primary_NTEE,
            string Specific_NTEE,
            string Address,
            string City,
            string State,
            string Zipcode,
            string Phone,
            string CreatedBy,
            DateTime CreatedDate,
            string ModifiedBy,
            DateTime ModifiedDate
            )
        {
            ListDictionary parameters = new ListDictionary();

            parameters.Add(new SqlParameter("@GrantID", SqlDbType.Int, 0), GrantID);
            parameters.Add(new SqlParameter("@Grant_Name", SqlDbType.NVarChar, 128), Grant_Name);
            parameters.Add(new SqlParameter("@Organization", SqlDbType.NVarChar, 128), Organization);
            parameters.Add(new SqlParameter("@Year", SqlDbType.DateTime, 0), Year);
            parameters.Add(new SqlParameter("@Amount", SqlDbType.Money, 0), Amount);
            parameters.Add(new SqlParameter("@Duration", SqlDbType.Int, 0), Duration);
            parameters.Add(new SqlParameter("@Primary_NTEE", SqlDbType.NVarChar, 512), Primary_NTEE);
            parameters.Add(new SqlParameter("@Specific_NTEE", SqlDbType.NVarChar, 512), Specific_NTEE);
            parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 512), Address);
            parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 128), City);
            parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 64), State);
            parameters.Add(new SqlParameter("@Zipcode", SqlDbType.NVarChar, 32), Zipcode);
            parameters.Add(new SqlParameter("@Phone", SqlDbType.NVarChar, 32), Phone);
            parameters.Add(new SqlParameter("@URL", SqlDbType.NVarChar, 32), "");
            parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.NVarChar, 128), CreatedBy);
            parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 0), CreatedDate);
            parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.NVarChar, 128), ModifiedBy);
            parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 0), ModifiedDate);

            ExecuteStoredProcedure("sp_Insert", parameters,false);

        }
		
        /// <summary>
        /// LoadFromSqlReader does not load data into your BusinessEntity
        /// </summary>
        /// <param name="sp">This must be a stored procedure</param>
        /// <returns>The new Key field ID</returns>
        public static int ExecuteStoredProcedure(string sp)
        {
            return ExecuteStoredProcedure(sp, null, CommandType.StoredProcedure, false);
        }

        /// <summary>
        /// This version allows you to pass in Parameters and thier values
        /// </summary>
        /// <param name="sp">This must be a stored procedure</param>
        /// <param name="Parameters">Two types of key/value pairs are allowed</param>
        /// <param name="hasReturnValue">Indicates whether the item has a return value</param>
        /// <returns>The new Key field ID</returns>
        public static int ExecuteStoredProcedure(string sp, ListDictionary Parameters, bool hasReturnValue)
        {
            return ExecuteStoredProcedure(sp, Parameters, CommandType.StoredProcedure, hasReturnValue);
        }


        /// <summary>
        /// This version allow you to use direct sql.
        /// </summary>
        /// <param name="sp">This must be a stored procedure</param>
        /// <param name="Parameters">Two types of key/value pairs are allowed, see <see cref="LoadFromSql"/></param>
        /// <param name="commandType">This property determines the type being passed in the "sp" parameter</param>
        /// <param name="hasReturnValue">This boolean value indicates whether the call should return a key value from the call</param>
        /// <returns>The new Key field ID</returns>
        public static int ExecuteStoredProcedure(string sp, ListDictionary Parameters, CommandType commandType, bool hasReturnValue)
        {
            int intReturn = -1;
            IDbCommand cmd;
            cmd = new SqlCommand() as IDbCommand;
            cmd.Connection = new SqlConnection() as IDbConnection;

            try
            {
                cmd.CommandText = sp;
                cmd.CommandType = commandType;
                IDataParameter p;

                if (Parameters != null)
                {
                    foreach (System.Collections.DictionaryEntry param in Parameters)
                    {
                        p = param.Key as IDataParameter;

                        if (null == p)
                        {
                            p.ParameterName = (string)param.Key;
                            p.Value = param.Value;
                        }
                        else
                        {
                            p.Value = param.Value;
                        }

                        cmd.Parameters.Add(p);
                    }
                }

                if (hasReturnValue)
                {
                    SqlParameter prmReturn = new SqlParameter("@Return", SqlDbType.Int);
                    prmReturn.Direction = ParameterDirection.ReturnValue;
                    cmd.Parameters.Add(prmReturn);
                }

                cmd.Connection.ConnectionString = ConfigurationSettings.AppSettings["DBConn"];
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();

                if (hasReturnValue)
                {
                    // Get the out parameters
                    SqlParameter prmReturn = (SqlParameter)cmd.Parameters["@Return"];
                    intReturn = Convert.ToInt32(prmReturn.Value);
                }

                return intReturn;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (cmd.Connection.State == ConnectionState.Open)
                    cmd.Connection.Close();
            }
        }

    }
}