标签: nullreferenceexception

为什么我不能检查连接字符串上的空引用?

可能是一个C#noob问题,所以不要激怒我.我试图这样做:

if (ConfigurationManager.ConnectionStrings["PrimaryConnectionString"].ConnectionString != null)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

但我一直得到一个System.NullReferenceException.我想,因为它返回一个我可以检查null并继续前进的字符串.我花了一段时间才找到正确的方法:

ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["PrimaryConnectionString"];
if (cs != null)
{
    this.Connection.ConnectionString = cs.ConnectionString;
}
Run Code Online (Sandbox Code Playgroud)

所以在其他情况下,比如检查Session对象的某些值,我会null像这样检查:

if (Session["EmployeeID"] != null)
{
    _EmployeeID = System.Convert.ToInt32(Session["EmployeeID"]);
}
Run Code Online (Sandbox Code Playgroud)

所以我只是想知道你怎么知道什么时候能做或不能做检查null?

c# asp.net null connection-string nullreferenceexception

2
推荐指数
1
解决办法
2246
查看次数

Page.User.Identity.IsAuthenticated返回未设置为对象实例的对象引用

这在我的本地站点上可以正常工作,但是将站点上载到实时服务器后,我就会得到stem.NullReferenceException:对象引用未设置为对象的实例

在此的第一行:

if (!Page.User.Identity.IsAuthenticated)
{
    pnlSignIn.Visible = true;
    pnlSignOut.Visible = false;
}
Run Code Online (Sandbox Code Playgroud)

asp.net authentication nullreferenceexception

2
推荐指数
1
解决办法
1930
查看次数

什么可以导致FindControl()抛出NullReferenceException?

我有一个用户控件我正在构建(ASP.NET 3.5,使用C#).

这个控件很大程度上基于另一个类似的控件(不幸的是,剪切和粘贴继承,但是没有简单的方法来抽象它).给我带来麻烦的行直接从其他控件复制,就像显示器的大部分一样.

相关的代码行如下:

Panel pnlForm = (Panel)e.Item.FindControl("pnlForm");
Literal ltrAvailableCount = (Literal)e.Item.FindControl("ltrAvailableCount");

DropDownList drpLanguage = (DropDownList)pnlForm.FindControl("drpLanguage");
DropDownList drpShipTo = (DropDownList)pnlForm.FindControl("drpShipTo");
HiddenField hdnAvailableProductId = (HiddenField)pnlForm.FindControl("hdnAvailableProductId");

DropDownList drpQuantity = (DropDownList)pnlForm.FindControl("drpQuantity");
HiddenField hdnSelectedStyle = (HiddenField)e.Item.FindControl("hdnSelectedStyle");
Label lblStyleName = (Label)e.Item.FindControl("lblSelectedStyle");
Run Code Online (Sandbox Code Playgroud)

pnlForm在上面找到了正确的,原样ltrAvailableCount.

如果我跳过drpQuantity,它和以下行正常工作.然而,当我运行的线路drpLanguage,drpShipTo或hdnAvailableProductId FindControl将引发NullReferenceException.

我并不是说它返回'null'并且我尝试访问返回对象的属性,该方法FindControl抛出异常.根据MSDN库,这是不可能的 - FindControl不会将任何内容列为潜在的抛出错误,它只是说如果它找不到Control,它将返回null.

什么可能导致FindControlNullReferenceException?

- - - - - - - - -编辑 - - - - - - - -

我还要提一下,如果我在即时窗口中运行三个有问题的行中的任何一行,我会得到正确的结果.我还可以看到在该控制ControlCollection …

.net c# asp.net findcontrol nullreferenceexception

2
推荐指数
2
解决办法
6923
查看次数

vb.net:iif如何给出空引用异常?

一直在看很多关于使用Iif()的帖子/文章.当我尝试像C/C#/ C++等那样使用像条件运算符这样的IIf()时,所有这一切都开始了.

我试图做的完全符合以下帖子的内容:

使用VB.NET IIF我得到NullReferenceException

但是,我实现的解决方案是从以下msdn站点借来的:

http://msdn.microsoft.com/en-us/library/27ydhh0d%28v=vs.80%29.aspx

之后我才了解了vb.net中的If()方法.

所以最后我写了一个函数,它返回适当的值(使用反射)来达到目的.但是那个方法(我写的)没有抛出任何异常.事实上,我能够检查函数内部类型的可空性.

Function ReturnValue(ByVal MyType As SomeType, ByVal PropertyName as String) As Object
    If MyType Is Nothing Then Return String.Empty
    Dim arrPropInfo As PropertyInfo() = MyType.GetType().GetProperties()
    Return arrPropInfo.Where(Function(x) x.Name = PropertyName).Item(0).GetValue(MyType, Nothing)
End Function
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否有一些内容写在Iif()内来抛出这样的错误? - NullReferenceException

If MyType Is Nothing Then Throw New NullReferenceException()
Run Code Online (Sandbox Code Playgroud)

或者这里有更大的工作吗?所以假设我想编写像iif这样的函数,如果参数列表中的某些内容为null,则抛出错误是上述方法的唯一方法吗?

vb.net iif-function nullreferenceexception

2
推荐指数
1
解决办法
1640
查看次数

MEF - 必须以某种方式设置导入还是可能为空?

基本上我有以下几点:

[Import]
private IEventAggregator EventAggregator { get; set; }

public void DoSomething()
{
    //Should I bother to check for null here before using EventAggregator?
}
Run Code Online (Sandbox Code Playgroud)

首先介绍几件事:

  1. 我的应用程序是否有可能没有MEF运行时异常并将该属性保留为null?
  2. 由于属性是私有的,我应该在每个方法中检查null吗?我在想,如果有一天我决定不使用MEF并做其他事情.我仍然会确保它在实例化时不能为空,所以我还需要防范它吗?
  3. 如果它被保护了,应该给我足够的理由来防范null,因为现在扩展类可以将它设置为null.或者,这是我不应该担心的事情(其他程序员扩展我的课程并用它做蠢事).

问题2还有以下问题:我们是否应该检查null,即使我们正在检查的属性是在类中维护的(即我们应该保护我们类的状态不允许这种情况).

c# wpf mef nullreferenceexception

2
推荐指数
1
解决办法
722
查看次数

findViewById()在一个活动中起作用,但在另一个活动中起作用

我试图将EditText从Activity1传递给Activity2.

Activity1代码:

public void openNextActivity() 
{
    Intent intent = new Intent("com.abc.xyz.ImageActivity"); 
    EditText myEditText = (EditText)findViewById(R.id.myEditText);

    int myEditTextId = myEditText.getId();
    //For Test purpose ----- starts
    // **Point1: next line of code works fine in this Activity1**
    EditText myEditTextTest = (EditText)findViewById(myEditTextId); 
    //For Test purpose ----- ends   

    intent.putExtra("myEditText", myEditTextId);

    startActivity(intent); 
}
Run Code Online (Sandbox Code Playgroud)

Activity2代码:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.comments_detail);

    Bundle extras = getIntent().getExtras();
    if(extras != null)
    {
        int myEditTextId = extras.getInt("myEditText");

        // Point2: next line of code displays the correct Id
        Log.d("tag","myEditTextId"+ myEditTextId); …
Run Code Online (Sandbox Code Playgroud)

android nullreferenceexception android-edittext android-view findviewbyid

2
推荐指数
1
解决办法
2061
查看次数

在winform应用程序中从Combobox读取值

我正在使用VS2010构建Windows窗体应用程序.我想读取用户从下拉列表中选择的值ComboBox并patientNo基于此生成.但是当我运行应用程序时,我得到了一个NullReferenceException.

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    string patientNumber;

    string gender = comboBox2.SelectedValue.ToString();
    if (gender != null)
    {
        if (gender == "Female")
        {
            var generator = new PatientNumberGenerator();
            patientNumber = generator.GeneratePatientNumber(Gender.Female);
            const string message = "patientNumber";

            const string caption = "Testing PatientNumber class";
            var result = MessageBox.Show(message, caption,
                                         MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Question);

        }
        else if (gender == "Male")
        {
            var generator = new PatientNumberGenerator();
            patientNumber = generator.GeneratePatientNumber(Gender.Male);
            const string message = "patientNumber";

            const string …
Run Code Online (Sandbox Code Playgroud)

c# nullreferenceexception winforms

2
推荐指数
1
解决办法
3万
查看次数

C#中的"| ="运算符是什么?

在研究错误的原因时,我遇到了这行代码:

Status |= (int)states.Reading;
Run Code Online (Sandbox Code Playgroud)

C#中的"| ="运算符是什么?

因此"状态"定义如下:

public static int Status 
Run Code Online (Sandbox Code Playgroud)

...使用存取器和mutator(或"getter"和"setter"),而"states"以这种方式定义:

[Flags]
public  enum states
Run Code Online (Sandbox Code Playgroud)

c# windows-ce nullreferenceexception enum-flags

2
推荐指数
1
解决办法
167
查看次数

控制器中的NullReferenceException c#

我NullReferenceException试着运行一个视图.我没有看到导致此问题的代码.有人可以解释这个问题吗?谢谢

这是Model类:

public class Catalogus: ICatalogus
{
    private readonly DbSet<Materiaal> materialen;
    private IEnumerable<Materiaal> materialenTest;
    private Firma firma;

    public Catalogus()
    {
        firma = new Firma("hh", "lol@gmail.com");
        materialenTest = new Materiaal[] { new Materiaal(5, 0, "1", "test", "test", "ts", firma, "wereldbol", "wereldbol", "lol", 0, true) };
    }

    public IEnumerable<Materiaal> VindAlleMaterialen()
    {
        return materialenTest.OrderBy(m => m.Naam);
    }

    public IEnumerable<Materiaal> ZoekOpTrefwoord(string trefwoord)
    {
        IEnumerable<Materiaal> gefilterdMaterialen = materialenTest.Where(mat => mat.GetType().GetProperty("naam").GetValue(this).Equals(trefwoord));

        return gefilterdMaterialen;
    }
} 
Run Code Online (Sandbox Code Playgroud)

具有NullRef异常的控制器:

这条线导致了这个问题.

IEnumerable materialen = catalogus.VindAlleMaterialen().OrderBy(m => m.Naam).ToList();

public …
Run Code Online (Sandbox Code Playgroud)

.net c# nullreferenceexception

2
推荐指数
1
解决办法
119
查看次数

SonarQube显示可能的空指针取消引用

此代码中可能的空指针解除引用错误:

if(!Util.isNull(dir)){
    if (dir.isDirectory()){
        if(!Util.isNull(dir.list()))
            if((!Util.isNull(dir.list().length))) // issue reported here
                if(dir.list().length == 0) // another issue reported here
                    if (dir.delete())
                        LOGGER.info("deleted:");
                    }
                }
Run Code Online (Sandbox Code Playgroud)

我该如何解决这些问题?

java null nullreferenceexception sonarqube

2
推荐指数
1
解决办法
1101
查看次数