2012-04-13 104 views
0

我有一个接口为什么我得到NullReferenceException?

public interface IConfig 
{ 
    string name { get; set; } 
    string address { get; set; } 
    int phone { get; set; } 

    List<string> children { get; set; } 
} 

这里是一个只有三个应用程序的设置不是四个像我在我的接口配置文件。

<add key="name" value="abc" /> 
<add key="address" value="100 Norin Street" /> 
<add key="phone" value="709-111-111111" /> 

现在启动时,我使用DictionaryAdapterFactory来填充app.config文件值。我在这里成功获取app.config的值。

private readonly IConfig _config; 
private readonly DictionaryAdapterFactory _factory; 
_factory = new DictionaryAdapterFactory(); 
_config = _config.GetAdapter<IConfig>(ConfigurationManager.AppSettings); 

现在在运行时我需要填写List类型的子值。但我得到空例外。为什么?

//loop 
_config.children.Add(item.values); 

这里有什么问题?

回答

4

缺少某处列表初始化?

_config.children = new List<string>() 
+0

我试过了,但后来发生此错误。 {“无法投射'System.String'类型的对象来键入'System.Collections.Generic.List'1 [System.String]'。”} – user1327064 2012-04-13 20:05:12

+2

显示更多代码,您的消息对我而言没有多大意义 – 2012-04-13 20:13:01

+0

@ user1327064哪行代码抛出“无法投射”异常? – phoog 2012-04-13 20:17:07

0

它会像下面一样吗?

_config.children.AddRange(item.values); 

当然,初始化也是必需的。

_config.children = new List<string>(); 
0

您在界面中将'Phone'定义为int,而AppSettings中的phone值不能转换为int。将其更改为字符串:

string phone { get; set; } 
相关问题