C# 为什么我';我得到一个错误,变量需要是静态的?
在类的顶部文件中,我添加了一个类:C# 为什么我';我得到一个错误,变量需要是静态的?,c#,.net,winforms,C#,.net,Winforms,在类的顶部文件中,我添加了一个类: public class World { public List<Continent> continents; public World() { continents = new List<Continent>(); } } public class Continent { public string name; public List<Country> c
public class World
{
public List<Continent> continents;
public World()
{
continents = new List<Continent>();
}
}
public class Continent
{
public string name;
public List<Country> countries { get; set; }
public Continent()
{
name = string.Empty;
countries = new List<Country>();
}
}
public class Country
{
public string name { get; set; }
public List<string> imageUrls { get; set; }
public Country()
{
name = string.Empty;
imageUrls = new List<string>();
}
}
我在表格1中得到的错误是:
ExtractImages.World.continents
在线:
foreach (ExtractImages.Continent continent in ExtractImages.World.continents)
严重性代码说明项目文件行抑制状态
错误CS0120非静态字段、方法或属性“ExtractImages.World.continents”需要对象引用
更新
在类文件中,我首先使用World,然后在form1中使用它:
在Form1中,我为World创建新实例时,它将全部为空
public void ImagesLinks()
{
try
{
int counter = 0;
foreach (string countryCode in countriescodes)
{
Country country = new Country();
country.name = countriesnames[counter];
List<string> imageUrl = new List<string>();
counter++;
for (int cnt = 0; cnt < DatesAndTimes.Count(); cnt++)
{
string imageUrlIrTrue = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "true";
string imageUrlIrFalse = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "false";
imageUrl.Add(imageUrlIrTrue);
imageUrl.Add(imageUrlIrFalse);
if (cnt == 9)
{
cnt = 0;
break;
}
}
country.imageUrls = imageUrl;
Europe.countries.Add(country);
}
world.continents.Add(Europe);
}
您应该首先创建类的实例,因为
大陆
是实例字段,而不是静态字段
,然后访问大陆
。但是,请记住,在构造函数中,您只创建了一个空列表。您不提供任何禁欲列表
。因此,每次创建新的世界对象时,大陆
都将是一个空的大陆
对象列表。你应该提供一些不同于空列表的东西,因为你的帖子中的foreach
是没有意义的
var world = new World();
foreach (var continent in world.continents)
{
// ...
}
当它不是静态对象时,您调用它就像调用静态对象一样,因为您将它用作静态类。您没有要求在该类型的实例上使用
.continets
。我忘了先提到我在类文件中使用World,因此如果我在form1中创建新的World实例,它将为空。我将更新我的问题,但这不是问题。你说你使用了世界
。怎么用?您没有创建这个类的实例吗?
ExtractImages.World world = new ExtractImages.World();
foreach (ExtractImages.Continent continent in world.continents)
{
Console.WriteLine(continent.name);
foreach (ExtractImages.Country country in continent.countries)
{
Console.WriteLine(country.name);
foreach (string imageUri in country.imageUrls)
{
Console.WriteLine(imageUri);
}
}
}
var world = new World();
foreach (var continent in world.continents)
{
// ...
}