你调用的对象是空的。有静态类吗? ! ConfigurationManager中 [英] Object reference not set to an instance of an object. With a static class? ! Configurationmanager

查看:67
本文介绍了你调用的对象是空的。有静态类吗? ! ConfigurationManager中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public string connectionString = ConfigurationManager.ConnectionStrings["HPDL160G62"].ConnectionString;





抛出



throws me

Object reference not set to an instance of an object.

错误。



谢谢



编辑我的APP.CONFIG



error.

thanks

EDIT MY APP.CONFIG

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="HPDL160G62" providerName="System.Data.SqlClient" connectionString="Data Source=HPDL160G62;Initial Catalog=Database;User ID=username;Password=password;"/>
  </connectionStrings>
  <appSettings>
    
  </appSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>





这是在类库中我正在从cl app执行。



我尝试过:



添加了静态关键字并删除但是我不知道为什么我会在静态类中出现这个错误?!

放在类的顶部并尝试放入方法但总是相同的



This is in a Class Library and I'm executing from cl app.

What I have tried:

added static keyword and removed but just I don't get why do I get this error with a static class ?!
placed just the top of the class and tried placing into methods but always the same

推荐答案

如果你将这一行分成几段,将会发生的事情变得更加明显

It will become more obvious what is happening if you break that line down into segments
var x = ConfigurationManager.ConnectionStrings;
var y = x["HPDL160G62"];
var z = y.ConnectionString;



x 不会有问题因为,正如你所说,它是一个静态类,所以你不需要一个实例。



但是 y null 因为集合中没有任何内容与HPDL160G62匹配。



因此,在分配给 z时会出现错误





集合中没有匹配项的原因是App.Config属于DLL。 ConfigurationManager只读取当前运行的程序集的app.config,即调用DLL的应用程序。



所以解决方法是在App.Config中使用此连接字符串调用应用程序



您仍然可以拥有DLL配置,但您必须手动读取它(我找到了一个很好的示例,如何执行此操作在哪里 [ ^ ])


x will not be a problem because, as you say, it's a static class so you don't need an instance.

But y is null because there is nothing in the collection that matches "HPDL160G62".

Therefore you get the error when assigning to z


The reason that there was no matching item in the collection is because the App.Config belonged to a DLL. ConfigurationManager only reads the app.config for the currently running assembly i.e. the application calling the DLL.

So the solution is to have this connection string in the App.Config for the calling application
OR
You can still have a DLL config but you will have to read it manually (I found a good example of how to do this here[^])


这篇关于你调用的对象是空的。有静态类吗? ! ConfigurationManager中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆