在我的应用程序中,我添加了一个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
}发布于 2013-11-04 10:00:24
首先,你让自己的生活变得很艰难。这很好(或者至少也很好,但容易得多;静态成员是否是一个好主意是一个单独的问题,并且在很大程度上取决于上下文):
public class Properties
{
public static string Type1 { get;set; }
}其次,这与属性无关,与调用null实例上的方法有关。您只需使用避免此问题的==,即
if (Properties.Type1 == "" || Properties.Type1 == null)
{
// Do something
}然而,为了方便起见,也有string.IsNullOrEmpty
if (string.IsNullOrEmpty(Properties.Type1))
{
// Do something
}发布于 2013-11-04 09:49:51
用这个代替:
if (string.IsNullOrEmpty(Properties.Type1))
{
// Do something
}发布于 2013-11-04 09:50:34
您正在以错误的方式执行空和空检查。
正确的方法是:
if (string.IsNullOrEmpty(Properties.Type1))
{
....
}https://stackoverflow.com/questions/19765086
复制相似问题