2017-11-11 121 views
-2

我有一个班级国家和另一班CountryBO。 从主类,我即时创建CountryBO,并在CountryBO的对象上,我打电话给一个方法定义在 CoountryBO类称为createCountry。 在这种方法中,我即时创建Country类的对象并设置一些变量,同时返回新创建的对象的引用。如何在C#中的列表中存储对象的引用?

public Country createCountry(String data) 
    { 
     string [] countryDetail = data.Split(','); 
     Country myCountry = new Country(); 
     myCountry._countryCode=countryDetail[2]; 
     myCountry._isdCode=countryDetail[1]; 
     myCountry._name=countryDetail[0]; 
     return myCountry; 
    } 

现在在调用主类,我想创建创建国家一流帽子的所有对象的列表。 但我无法做到。

CountryBO myCountryBO = new CountryBO(); 
    Country[] countryList = new Country[]; 
    countryList = myCountryBO.createCountry(countryDetails); 
    countryCount +=1; 
+1

你可以发布两个类的定义吗?你还遇到什么错误? –

+0

改为使用'List ',那么你可以使用'list.Add(myCountryBO.createCountry)'。数组不像功能丰富的通用列表。 – Charleh

+0

问题不明确,是否有可能countryCount需要静态?我不确定你想要完成什么。 – Protium

回答

1

您需要使用List<Country>而不是Country[]

试试这个:

Country[] countryList = new List<Country>(); 
CountryBO myCountryBO = new CountryBO(); 
countryList.Add(myCountryBO.createCountry(countryDetails)); 
0

我想这一点,但没有奏效。

Country[] countryList = new List<Country>(); 
CountryBO myCountryBO = new CountryBO(); 
countryList.Add(myCountryBO.createCountry(countryDetails)); 

在的地方,我做了什么被抓获,他在列表中返回的对象引用,然后使用ToArray的方法在列表类转换帽子阵列。

List<Country> countryList_temp = new List<Country>(); 
countryList_temp.Add(myCountryBO.createCountry(countryDetails)); 
Country[] countryList = countryList_temp.ToArray(); 
相关问题