物业正在制造麻烦

Dha*_*alR 0 c# winforms

在我的应用程序中,我添加了一个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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我以我的一个表单访问此属性时,我收到错误.例如

if (Properties.Type1.Equals(string.Empty) || Properties.Type1.Equals(null))
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

首先,你为自己的生活艰难.这是罚款(或者至少,只是作为好,但更容易;静态成员是否是一个好主意是一个单独的问题,并且在很大程度上取决于上下文):

public class Properties
{   
    public static string Type1 { get;set; }
}
Run Code Online (Sandbox Code Playgroud)

其次,这与属性无关,而与在null实例上调用方法有关.你可以使用==它来避免这个问题,即

if (Properties.Type1 == "" || Properties.Type1 == null)
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

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

if (string.IsNullOrEmpty(Properties.Type1))
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)