C# 集合初始化为何引发NullReferenceException
以下代码抛出一个C# 集合初始化为何引发NullReferenceException,c#,.net,collections,nullreferenceexception,duck-typing,C#,.net,Collections,Nullreferenceexception,Duck Typing,以下代码抛出一个NullReferenceException: internal class Foo { public Collection<string> Items { get; set; } // or List<string> } class Program { static void Main(string[] args) { new Foo() { Items =
NullReferenceException
:
internal class Foo
{
public Collection<string> Items { get; set; } // or List<string>
}
class Program
{
static void Main(string[] args)
{
new Foo()
{
Items = { "foo" } // throws NullReferenceException
};
}
}
内部类Foo
{
公共集合项{get;set;}//或列表
}
班级计划
{
静态void Main(字符串[]参数)
{
新富()
{
Items={“foo”}//引发NullReferenceException
};
}
}
collection
实现了Add()
方法,但是为什么在这种情况下集合初始化器不工作,为什么会引发NullReferenceExceptionItems=new collection(){“foo”}
是初始化它的唯一正确方法声明了
Foo.Items
,但从未分配集合的实例,因此.Items
为null
修正:
内部类Foo
{
公共集合项{get;set;}//或列表
}
班级计划
{
静态void Main(字符串[]参数)
{
新富()
{
Items=新集合{“foo”}//不再抛出NullReferenceException:-)
};
}
}
在Foo
构造函数中,要初始化集合
internal class Foo
{
public Foo(){Items = new Collection(); }
public Collection<string> Items { get; set; } // or List<string>
}
class Program
{
static void Main(string[] args)
{
new Foo()
{
Items = { "foo" } // throws NullReferenceException
};
}
}
内部类Foo
{
public Foo(){Items=new Collection();}
公共集合项{get;set;}//或列表
}
班级计划
{
静态void Main(字符串[]参数)
{
新富()
{
Items={“foo”}//引发NullReferenceException
};
}
}
您从未实例化项。试试这个
new Foo()
{
Items = new Collection<string> { "foo" }
};
谢谢大家。因为summary集合初始值设定项不创建集合本身的实例,而只是使用Add()将项添加到现有实例中,如果实例不存在,则抛出NullReferenceException
一,
内部类Foo
{
内部Foo()
{
Items=新集合();
}
公共集合项{get;private set;}
}
var foo=new foo()
{
Items={“foo”}//foo.Items包含1个元素“foo”
};
二,
内部类Foo
{
内部Foo()
{
Items=新集合();
项目。添加(“foo1”);
}
公共集合项{get;private set;}
}
var foo=new foo()
{
Items={“foo2”}//foo.Items包含两个元素:“foo1”、“foo2”
};
初始化时是否尝试过使用new
?这并不能回答他的问题,请参见#2。@如果要更新我的答案,请立即检查
new Foo()
{
Items = new Collection<string> { "foo" }
};
internal class Foo
{
internal Foo()
{
Items = new Collection<string>();
}
public Collection<string> Items { get; private set; }
}
internal class Foo
{
internal Foo()
{
Items = new Collection<string>();
}
public Collection<string> Items { get; private set; }
}
var foo = new Foo()
{
Items = { "foo" } // foo.Items contains 1 element "foo"
};
internal class Foo
{
internal Foo()
{
Items = new Collection<string>();
Items.Add("foo1");
}
public Collection<string> Items { get; private set; }
}
var foo = new Foo()
{
Items = { "foo2" } // foo.Items contains 2 elements: "foo1", "foo2"
};