首页 新闻 赞助 找找看

c# using 语句中使用的类型错误

0
悬赏园豆:15 [已解决问题] 解决于 2014-01-02 22:50
 1 using System;
 2 using System.Collections;
 3 
 4 public static DictionaryEntry[] GetEntry(IDictionary dictionary)
 5 {
 6    DictionaryEntry[] entryArray = new DictionaryEntry[dictionary.Count];
 7    using(IDictionaryEnumerator enumerator = dictionary.GetEnumerator())
 8   {
 9     int num = 0;
10     while (enumerator.MoveNext())
11     {
12       entryArray[num++] = enumerator.Entry;
13     }
14    return entryArray;
15   }
16 }

 错误"System.Collections.IDictionaryEnumerator”: using 语句中使用的类型必须可隐式转换为“System.IDisposable” 

c#
fredxiong的主页 fredxiong | 初学一级 | 园豆:178
提问于:2014-01-02 21:40
< >
分享
最佳答案
0

using会自动调用System.IDisposable下的Dispose方法来释放非托管资源,

System.Collections.IDictionaryEnumerator  它没继承System.IDisposable接口,所以不能用。

另外,System.Collections.IDictionaryEnumerator的实例不需要手动释放,C#会自己处理的。

        public static DictionaryEntry[] GetEntry(IDictionary dictionary)
        {
            DictionaryEntry[] entryArray = new DictionaryEntry[dictionary.Count];
            IDictionaryEnumerator enumerator = dictionary.GetEnumerator();
            int num = 0;
            while (enumerator.MoveNext())
            {
                entryArray[num++] = enumerator.Entry;
            }
            return entryArray;
        }

直接实例化使用就可以了。

收获园豆:15
aehyok | 小虾三级 |园豆:1212 | 2014-01-02 21:51
其他回答(2)
0

Dictionary没有直接或间接实现IDispose接口,所以没法用using释放资源

using功能:

1.引入命名空间 using system;

2.起别名  using sb = System.Text; 

3.释放资源  using(SqlConnection con=new SqlConnection(conStr)){  //执行体}

秋壶冰月 | 园豆:5903 (大侠五级) | 2014-01-02 22:38
0

要使用using,请确保你的类实现了IDispose接口。实际上使用using,完毕后就是自动调用你实现的Dispose方法。

幻天芒 | 园豆:37175 (高人七级) | 2014-01-02 22:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册