0

在我的应用程序中,我添加了一个 Properties.cs 文件,其中包含我将在整个应用程序中使用的属性。我得到 NullReferenceException =>Object reference not set to an instance of an object.

这是 Properties.cs 的代码

public class Properties
{
    private static string type1;

    public static string Type1
    {
        get
        {
            return type1;
        }
        set
        {
            type1= value;
        }
    }
}

当我以我的一种形式访问此属性时,我遇到了错误。例如

if (Properties.Type1.Equals(string.Empty) || Properties.Type1.Equals(null))
{
    // Do something
}
4

4 回答 4

5

首先,你让自己的生活变得艰难。这很好(或者至少一样好,但容易得多;静态成员是否是一个好主意是一个单独的问题,并且很大程度上取决于上下文):

public class Properties
{   
    public static string Type1 { get;set; }
}

其次,这与属性无关,与在null实例上调用方法有关。您可以使用==which 避免此问题,即

if (Properties.Type1 == "" || Properties.Type1 == null)
{
    // Do something
}

但是,为方便起见,还有string.IsNullOrEmpty

if (string.IsNullOrEmpty(Properties.Type1))
{
    // Do something
}
于 2013-11-04T10:00:24.353 回答
2

改用这个:

if (string.IsNullOrEmpty(Properties.Type1))
{
    // Do something
}
于 2013-11-04T09:49:51.320 回答
2

您正在以错误的方式进行 null 和空检查。

正确的方法是:

if (string.IsNullOrEmpty(Properties.Type1))
{
 ....
}
于 2013-11-04T09:50:34.033 回答
0

你可以这样做

if (String.IsNullOrEmpty(Properties.Type1))
{
    // Do something
}

但是如果你想要一个默认值,那么我建议你在静态构造函数中设置它。

于 2013-11-04T09:51:48.430 回答