我得到了一个名为classList的类列表。此列表中的每个类都有一个带有字符串参数的构造函数,该参数包含有关该类的一些信息。我想迭代classList,然后将所有构造函数参数添加到stringarray。 我怎么能这样做?
public Main()
{
classList = new List<class>();
class1 = new class1("class1 information");
class2 = new class2("class2 information");
classList.Add(class1);
classList.Add(class2);
}
public void getConstructorParametersToList()
{
string[] myArrayList = null;
for(int i = 0; i < classList.Count; i++)
{
//Add the parameters from the constructors to a string array
myArrayList[i] = parameterfromconstructor
}
}
public void doSomething()
{
foreach (string s in myArrayList)
{
Console.WriteLine(s);
}
}
//Output:
//Class1 information
//Class2 information
答案 0 :(得分:1)
您可以将该构造函数参数存储在类字段或属性中,然后再访问它。
public interface IParameterizedClass
{
string ClassParameter {get}
}
public class class1 : IParameterizedClass
{
public string ClassParameter {get; private set;}
public class1(string someParameter)
{
// do some work
ClassParameter = someParameter;
}
}
public class class2 : IParameterizedClass
{
public string ClassParameter {get; private set;}
public class2(string someParameter)
{
// do some work
ClassParameter = someParameter;
}
}
public void getConstructorParametersToList()
{
string[] myArrayList = null;
for(int i = 0; i < classList.Count; i++)
{
//Add the parameters from the constructors to a string array
myArrayList[i] = (classList[i] as IParameterizedClass).ClassParameter;
}
}