一次失败的尝试

      下午想自己定义一个HtmlHelper来实现传入一个人枚举类型时,能实现一个下拉框.实现

       枚举定义的值如下:

public enum CheckStatus
    {
        未审核=0,
        已审核=1,
        审核失败=2
    }

       想要实现的Html代码如下:

<select id="checkStatus" name="CheckStatus"  >
<option  value="0">未审核</option>
<option  value="1">已审核</option>
<option  value="2">审核失败</option>
</select>

       于是就需要遍历枚举,分别获取枚举项和该项的对应值。于是就写了下面一个方法

public void GetItemsAndValues(Type enumType, out string[] itemArray, out string[] valueArray)
{
itemArray
=Enum.GetNames(enumType);
valueArray
= new string[itemArray.Length];
Action
<string, int> action = delegate(string item, int i)
{ valueArray[i]
= Enum.Format(enumType, Enum.Parse(enumType, item), "d"); };
itemArray.ForEach(action);

}

 测试调用的方法:

public void Test()
{

Type enumType
= typeof(CheckStatusEnum);
string[] itemArray = new string[]{};
string[] valueArray=new string[]{};
this.GetItemsAndValues(enumType, out itemArray,out valueArray);

}

      可是很不幸,这样是不能运行的,因为“不能在匿名方法、lambda 表达式或查询表达式内使用 ref 或 out 参数”。于是不得不将代码修改为下面这样。

public void GetItemsAndValues(Type enumType, out string[] itemArray, out string[] valueArray)
{
itemArray
=Enum.GetNames(enumType);
valueArray
= new string[itemArray.Length];
for (int i = 0; i <itemArray.Length; i++)
{
valueArray[i]
= 
Enum.Format(enumType, Enum.Parse(enumType, itemArray[i]),
"d");
}
}

       这样就能得出正确结果。在审核代码时还发现了一个不好的地方,就是在Test方法里面,发现这样写的话不好,下面的写法会先给itemArray,valueArray这两个堆栈上的指针分配一个地址,而我们在函数里面给itemArray,valueArray这两个堆栈上的指针分配了一个新的地址。这样之前的地址需要GC进行回收,浪费内存和性能。

       string[]itemArray=new string[]{};

       string[]valueArray=new string[]{};

public void GetItemsAndValues(Type enumType, out string[] itemArray, out  string[] valueArray)
        {
            itemArray =Enum.GetNames(enumType);
            valueArray = new string[itemArray.Length];
            Action<string, int> action = delegate(string item, int i)
            { valueArray[i] = Enum.Format(enumType, Enum.Parse(enumType, itemArray[i]), "d"); };
            itemArray.ForEach(action);
           
        }
posted @ 2011-03-31 16:35  雁北飞  阅读(421)  评论(0编辑  收藏  举报