C#在使用构造函数后将值添加到实例
问题描述:
我可以在使用构造函数之后将值添加到对象的实例吗?C#在使用构造函数后将值添加到实例
例如我有这个代码。我必须制作一个需要数字n的对象列表,以及时间(作为参数收到)。问题是时间可能在任何地方,所以我不能在构造函数中使用它。
for(int i=0; i<=t.Count; i++) { *add time to t[i]* }
如何做到这一点:
public List<IAction> Dispatch(string[] arg)
{
int time;
int i = 0;
int j = 0;
List<IAction> t = new List<IAction>(10);
do
{
if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20)
{
t.Add(new ComputeParam(int.Parse(arg[j])));
i++;
j++;
}
else
{
if (arg[i][0] == '/' && arg[i][1] == 't')
{
Options opt = new Options();
j++;
time=opt.Option(arg[i]); //sets the time 0,1000 or 2000
}
}
} while (i != arg.Length);
return t;
}
整理上榜我可以这样做之后?
在此先感谢!
编辑:
这里是ComputeParam类
public class ComputeParam : IAction
{
int n;
int time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this.n = n;
}
public void run()
{
Factorial Fact = new Factorial();
Fact.Progression += new Factorial.ProgressEventHandler(Progress);
Console.WriteLine(" ");
Console.Write("\n" + "Partial results : ");
Console.CursorLeft = 35;
Console.Write("Progress : ");
int Result = Fact.CalculateFactorial(n, time);
Console.WriteLine(" ");
Console.WriteLine("The factorial of " + n + " is : " + Result);
Console.WriteLine("Press Enter to continue...");
Console.CursorTop -= 2;
Console.CursorLeft = 0;
Console.ReadLine();
}
public void Progress(ProgressEventArgs e)
{
int result = e.getPartialResult;
int stack_value = e.getValue;
double max = System.Convert.ToDouble(n);
System.Convert.ToDouble(stack_value);
double percent = (stack_value/max) * 100;
Console.CursorLeft = 18;
Console.Write(result + " ");
Console.CursorLeft = 46;
Console.Write(System.Convert.ToInt32(percent) + "% ");
}
}
答
如果对象有一个公共财产,我不明白为什么不能。
编辑:看起来您需要为您的班级添加公共属性。还要注意,考虑到有一个公共构造函数需要0个参数,您还应该为n添加一个属性。
public class ComputeParam : IAction
{
int _n;
int _time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this._n = n;
}
public int Time
{
get { return this._time; }
set { this._time = value; }
}
public int N
{
get { return this._n; }
set { this._n = value; }
}
for(int i = 0; i < t.Count; i++)
{
((ComputeParam)t[i]).Time = 6;
}
试试吧,告诉我们。 – Oded 2012-08-06 12:18:54
向我们展示您的ComputerParam类。 – twoflower 2012-08-06 12:19:20