NET问答: 为什么 IEnumerablestring 不能被初始化?
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                NET问答: 为什么 IEnumerablestring 不能被初始化?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                咨詢區(qū)
- markzzz: 
我有下面的一個對象。
IEnumerable<string>?m_oEnum?=?null;現(xiàn)在我想初始化它,然后我做了下面的嘗試。
IEnumerable<string>?m_oEnum?=?new?IEnumerable<string>()?{?"1",?"2",?"3"};很遺憾,編譯器報錯了。。。
Cannot?create?an?instance?of?the?abstract?type?or?interface?'IEnumerable<string>'請問這種情況我該怎么合理的處置呢?
回答區(qū)
- Community: 
微軟早就考慮到了這種情況,你可以使用微軟自己提供的Enumerable.Empty() 擴展方法即可,簽名如下:
public?static?class?Enumerable{public?static?IEnumerable<TResult>?Empty<TResult>(){return?EmptyEnumerable<TResult>.Instance;}}接下來就可以這么用了。
IEnumerable<string>?m_oEnum?=?Enumerable.Empty<string>();如果不想用底層框架現(xiàn)成的,可以自己用一個實現(xiàn)類初始化。
IEnumerable<string>?m_oEnum?=?new?string[]{};- ChrisF: 
IEnumerable 是一個接口,所以你無法直接對它進行初始化,不過你可以使用實現(xiàn)它接口方法的實現(xiàn)類來初始化,比如: List。
IEnumerable<string>?m_oEnum?=?new?List<string>()?{?"1",?"2",?"3"?};然后你就可以把 m_oEnum 傳參到所有接收 IEnumerable<string> 的地方啦。
點評區(qū)
這是一個很基礎的問題,很多初學者在混入了泛型參數(shù)之后就搞蒙了,而現(xiàn)實開發(fā)中也常會遇到這種場景,學習了。
總結
以上是生活随笔為你收集整理的NET问答: 为什么 IEnumerablestring 不能被初始化?的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: .NET Core with 微服务 -
- 下一篇: 不要笑!写 | 还是 || ,还真是一个
