2012年5月15日

C# []、List、Array、ArrayList 区别及应用

 

[] 是针对特定类型固定长度的。

List 是针对特定类型任意长度的。

Array 是针对任意类型固定长度的。

ArrayList 是针对任意类型任意长度的。

Array 和 ArrayList 是通过存储 object 实现任意类型的,所以使用时要转换。

应用示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // System.Int32 是结构
        int[] arr = new int[] { 1, 2, 3 };
        Response.Write(arr[0]); // 1
        Change(arr);
        Response.Write(arr[0]); // 2

        // List 的命名空间是 System.Collections.Generic
        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        list.Add(3);
        Response.Write(list[0]); // 1
        Change(list);
        Response.Write(list[0]); // 2

        // Array 的命名空间是 System
        Array array = Array.CreateInstance(System.Type.GetType("System.Int32"), 3); // Array 是抽象类,不能使用 new Array 创建。
        array.SetValue(1, 0);
        array.SetValue(2, 1);
        array.SetValue(3, 2);
        Response.Write(array.GetValue(0)); // 1
        Change(array);
        Response.Write(array.GetValue(0)); // 2

        // ArrayList 的命名空间是 System.Collections
        ArrayList arrayList = new ArrayList(3);
        arrayList.Add(1);
        arrayList.Add(2);
        arrayList.Add(3);
        Response.Write(arrayList[0]); // 1
        Change(arrayList);
        Response.Write(arrayList[0]); // 2
    }

    private void Change(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] *= 2;
        }
    }

    private void Change(List<int> list)
    {
        for (int i = 0; i < list.Count; i++) // 使用 Count
        {
            list[i] *= 2;
        }
    }


    private void Change(Array array)
    {
        for (int i = 0; i < array.Length; i++) // 使用 Length
        {
            array.SetValue((int)array.GetValue(i) * 2, i); // 需要类型转换
        }
    }

    private void Change(ArrayList arrayList)
    {
        for (int i = 0; i < arrayList.Count; i++) // 使用 Count
        {
            arrayList[i] = (int)arrayList[i] * 2; // 需要类型转换
        }
    }
}

posted @ 2012-05-15 16:31 leon_ALiang 阅读(3) 评论(0) 编辑


2012年4月17日

ParseExact for Strings?

 

The DateTime.ParseExact() method has come in handy on a number of occasions. I really wish there was something similar for strings as sometimes you need to grab specific components of a string. You can use regex directly but that seems a little cumbersome. So here is an extension method that works like the DateTime.ParseExact() but returns an array of strings.

string value = "2/17/2009 10:57:42 AM...Executing file 26 of 81 files";
string[] parts = value.ParseExact("{0}...Executing file {1} of {2} files");
foreach (string part in parts)
    Console.WriteLine(part);
Console.ReadKey();
image 

Implementation:

public static class StringExtensions
{
    public static string[] ParseExact(
        this string data, 
        string format)
    {
        return ParseExact(data, format, false);
    }

    public static string[] ParseExact(
        this string data, 
        string format, 
        bool ignoreCase)
    {
        string[] values;

        if (TryParseExact(data, format, out values, ignoreCase))
            return values;
        else
            throw new ArgumentException("Format not compatible with value.");
    }

    public static bool TryExtract(
        this string data, 
        string format, 
        out string[] values)
    {
        return TryParseExact(data, format, out values, false);
    }

    public static bool TryParseExact(
        this string data, 
        string format, 
        out string[] values, 
        bool ignoreCase)
    {
        int tokenCount = 0;
        format = Regex.Escape(format).Replace("\\{", "{");

        for (tokenCount = 0; ; tokenCount++)
        {
            string token = string.Format("{{{0}}}", tokenCount);
            if (!format.Contains(token)) break;
            format = format.Replace(token,
                string.Format("(?'group{0}'.*)", tokenCount));
        }

        RegexOptions options = 
            ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;

        Match match = new Regex(format, options).Match(data);

        if (tokenCount != (match.Groups.Count - 1))
        {
            values = new string[] { };
            return false;
        }
        else
        {
            values = new string[tokenCount];
            for (int index = 0; index < tokenCount; index++)
                values[index] = 
                    match.Groups[string.Format("group{0}", index)].Value;
            return true;
        }
    }
}
原帖:
http://blog.mikeobrien.net/2009/02/parseexact-for-strings.html

posted @ 2012-04-17 14:20 leon_ALiang 阅读(4) 评论(0) 编辑


2012年2月3日

最近用到了点编译的知识,顺便补习了一下。

词法分析:词法分析阶段是编译过程的第一个阶段。这个阶段的任务是从左到右一个字符一个字符地读入源程序,即对构成源程序的字符流进行扫描然后根据构词规则识别单词(也称单词符号或符号)。

语法分析:一个语法分析的引擎就让人很是头疼,它是一个让人陌生的名词,它能根据你的语法描述就能生成一个有限自动机,然后根据这个有限自动机判断程序是否有语法错误,这个过程就是一个很神奇很困难的过程。

语义分析:语义分析是编译中最实质的阶段,将语法分析的正确的内容分析成语法树。对源程序做出解释,引起源程序发生质的变化。

 

写语义分析的时候思路是清晰的,因为你能清晰的知道语义分析是干什么的,知道它的内部实现是什么样的。而它的内部实现没有用到什么特殊的没有见过的算法。

 

附上一张图:

posted @ 2012-02-03 16:17 leon_ALiang 阅读(19) 评论(0) 编辑


2011年12月21日

直接上代码了,以后碰到类似的就直接用了

public static TKey FindKeyByValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TValue value)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");

foreach (KeyValuePair<TKey, TValue> pair in dictionary)
if (value.Equals(pair.Value)) return pair.Key;

throw new Exception("the value is not found in the dictionary");
}

  public static T Clone<T>(this T source)
{
T Cloned = (T)Activator.CreateInstance(source.GetType());

(from Property in source.GetType().GetProperties()

where Property.GetGetMethod() != null && Property.GetSetMethod() != null
select Property).ToList().ForEach(Property =>
{
// Check if the object inherits from ICollection (The ICollection interface is the base interface for classes in the System.Collections namespace
if (!Property.PropertyType.GetInterfaces().Contains(typeof(ICollection)))
{
object PropertyValue = Property.GetGetMethod().Invoke(source, Property.GetGetMethod().GetParameters());

if (PropertyValue != null && PropertyValue is DependencyObject) { PropertyValue = PropertyValue.Clone(); }

// if PropertyValue is not a value type and is itself a dependency object, it must be "cloned" as well
Property.GetSetMethod().Invoke(Cloned, new object[] { PropertyValue });
}
else if (Property.PropertyType.GetInterfaces().Contains(typeof(ICollection)))
{
ICollection CollectionValue = (ICollection)Property.GetGetMethod().Invoke(source, new object[] { }); Property.SetValue(Cloned, CollectionValue, null);
}

});
return Cloned;
}



posted @ 2011-12-21 09:58 leon_ALiang 阅读(14) 评论(0) 编辑


2011年12月14日

在日常开发中,经常会碰到对Dictionary的大量操作,判断等。当然可以用Dictionary本省,也可以重写一个符合自己逻辑处理的Dictionary.

public class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
    {
        IList<TKey> keys = new List<TKey>();
        IList<TValue> values = new List<TValue>();

        public MyDictionary() 
        {
        }

        public MyDictionary(IDictionary<TKey, TValue> dictionary)
        {
            foreach (var key in dictionary.Keys)
            {
                this[(TKey)key] = (TValue)dictionary[key];
            }
        }

        public ICollection<TKey> keySet()
        {
            return this.Keys;
        }

        public bool IsEmpty()
        {
            return (this.Count == 0);
        }

        #region MyDictionary<TKey,TValue> Members

        public void Add(TKey key, TValue value)
        {
            keys.Add(key);
            values.Add(value);
        }

        public bool ContainsKey(TKey key)
        {
            return keys.Contains(key);
        }

        public ICollection<TKey> Keys
        {
            get { return new ReadOnlyCollection<TKey>(keys); }
        }

        public bool Remove(TKey key)
        {
            int removeLocation = keys.IndexOf(key);
            if (removeLocation < 0)
                return false;

            values.RemoveAt(removeLocation);
            keys.RemoveAt(removeLocation);
            return true;
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            if (keys.Contains(key))
            {
                value = values[keys.IndexOf(key)];
                return true;
            }
            value = default(TValue);
            return false;
        }

        public ICollection<TValue> Values
        {
            get { return new ReadOnlyCollection<TValue>(values); }
        }

        public TValue this[TKey key]
        {
            get
            {
                if (values.Count <= 0)
                    return default(TValue);
                else
                {
                    int nIndex = keys.IndexOf(key);
                    if (nIndex < 0)
                        return default(TValue);
                    else
                        return values[nIndex];
                }
            }
            set
            {
                if (keys.Contains(key))
                    values[keys.IndexOf(key)] = value;
                else
                    Add(key, value);
            }
        }

        #endregion

        #region ICollection<KeyValuePair<TKey,TValue>> Members

        public void Add(KeyValuePair<TKey, TValue> item)
        {
            Add(item.Key, item.Value);
        }

        public void Clear()
        {
            keys.Clear();
            values.Clear();
        }

        public bool Contains(KeyValuePair<TKey, TValue> item)
        {
            if (keys.Contains(item.Key))
                return (this[item.Key].Equals(item.Value));
            return false;
        }

        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array was null");
            }
            if ((arrayIndex < 0) || (arrayIndex > array.Length))
            {
                throw new ArgumentOutOfRangeException("arrayIndex");
            }
            if ((array.Length - arrayIndex) < this.Count)
            {
                throw new ArgumentException("Array plus offset is too small");
            }

            foreach (KeyValuePair<TKey, TValue> keyValue in this)
            {
                array[arrayIndex++] = keyValue;
            }

        }

        public int Count
        {
            get { return keys.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(KeyValuePair<TKey, TValue> item)
        {
            if (keys.Contains(item.Key) && values[keys.IndexOf(item.Key)].Equals(item.Value))
            {
                Remove(item.Key);
                return true;
            }
            return false;
        }

        #endregion

        #region IEnumerable<KeyValuePair<TKey,TValue>> Members

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            int index = 0;
            foreach (TKey key in keys)
                yield return new KeyValuePair<TKey, TValue>(key, values[index++]);
        }

        #endregion

        #region IEnumerable Members

        IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.Keys.GetEnumerator();
        }

        #endregion
    }

 

posted @ 2011-12-14 10:49 leon_ALiang 阅读(46) 评论(0) 编辑


2011年12月8日

摘要: “开放-封闭”原则是我们OOD的目标,达到这一目标的主要机制就是“依赖倒转”原则(DIP)这个原则的内容是:要依赖于抽象,不要依赖于具体。或者说是:要针对接口编程,不要对实现编程(Program to an interface, not an implementation)。对于抽象层次来说,它是一个系统的本质的概括是系统的商务逻辑和宏观的,战略性的决定,是必然性的体现;具体的层次则是与实现有关的算法和逻辑,一些战术性的决定,带有相当大的偶然性。传统的过程性系统设计办法倾向于使高层次的模块依赖于低层次的模块;抽象层次依赖于具体层次。这实际上就是微观决定宏观,战术决定战略,偶然决定必然。依赖倒转阅读全文

posted @ 2011-12-08 18:03 leon_ALiang 阅读(25) 评论(0) 编辑


2011年12月1日

摘要: 从内存的角度来说,子类实例化的时候,会为抽象类划出来一块堆内存,用来存储抽象类的成员变量,而Interface没有成员变量,所以就不用开辟堆内存。(当然用来存储函数首地址的空间是省不了的)。阅读全文

posted @ 2011-12-01 11:00 leon_ALiang 阅读(33) 评论(0) 编辑


2011年11月23日

摘要: 很长时间没有做过客户端的东西了,最近在WPF。今天在code refactor的过程中尝试了一把add event.Background:分别有Text的Datepicker和ComboBox的Datepicker打算把单个的Calendar拿出来做一个usercontrol.把选中的日期付给textbox,也就是说这个usercontrol里需要在选中日期的事件里来处理。选中日期的事件: private void calender_SelectedDatesChanged(object sender, SelectionChangedEventArgs e) { ...阅读全文

posted @ 2011-11-23 18:21 leon_ALiang 阅读(89) 评论(0) 编辑


2011年11月16日

摘要: 浅拷贝:给对象拷贝一份新的对象。-----只对值类型(或string类型)分配新的内存地址。深拷贝:给对象拷贝一份全新的对象。-----对值类型分配新的内存地址,引用类型以及引用类型的内部字段分配新的地址。通俗讲,浅拷贝只拷贝指针的内容,深拷贝拷贝指针指向的内存块的值。如下: public object Clone() { Student B = new Student(); B.Name = this.Name; B.Age = this.Age; //浅拷贝 B.Class = this.Class; //深拷贝 B.Class = new Classroom(); B.Class.Nam阅读全文

posted @ 2011-11-16 22:29 leon_ALiang 阅读(17) 评论(0) 编辑


2011年10月24日

摘要: 或许大家觉得这东西过于简单以至于无需一提? 但是在我参与的项目中,其实很多适用于 Extension Method 的地方,大家却根本就没有意识到。Extension Method 的一个主要用途便是构造辅助方法。 在编程中为了抽象和简化,我们会把一些常用但又不好专门为它们创建一个对象类的方法放到所谓的Helper 中,在使用时调用 Helper.Xxxx()。例如:public static class Helper{ public static SecureString ToSecureString(string value) { SecureString res...阅读全文

posted @ 2011-10-24 15:48 leon_ALiang 阅读(96) 评论(0) 编辑


posts - 20, comments - 0, trackbacks - 0, articles - 0

Copyright © leon_ALiang