我无法创建包含对象内部属性数组的对象 [英] I cannot create object that contains arrays of property inside object

查看:81
本文介绍了我无法创建包含对象内部属性数组的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c#MVC3的新开发人员. 我有一个问题,我无法创建包含对象内部属性数组的对象.

I am a new developer to c# MVC3. I have a problem that I cannot create object that contains arrays of property inside object.

例如,我要为10个数组创建实例ABC.Property [].

For example, I want to create instance ABC.Property[] for 10 arrays.

ABC.Property [0]

ABC.Property[0]

ABC.Property [1]

ABC.Property[1]

ABC.Property [2] ..... .... ABC.Property [10]

ABC.Property[2] ..... .... ABC.Property[10]

我使用调试模式进行检查,发现ABC.Property []为空.因此,我无法将值添加回该对象的数组.

I used debug mode to check and found out that ABC.Property[] is null. So i cannot add the value back to that object's array.

如何使用属性数组创建对象?

How to crate object with propeties's array?

谢谢.

namespace finance3.Models
{
public class Expected_and_Risk
{


    public decimal[] Prop { get; set; }
    public decimal[] Forecast { get; set; }
    public string[] Name { get; set; }
    public decimal[] AxB { get; set; }
    public decimal[] PowAxB { get; set; }


    public decimal  ExpectValue(Expected_and_Risk abc)
    {

        decimal count = abc.Forecast.Count();

        Expected_and_Risk Result = new Expected_and_Risk();

        for (int i = 0 ; i < count ; i++)
        {
            // here is the problem
            // i cannot add new data to array because it has no dimemsion and i tried this
            //
            // Expected_and_Risk[] Result = new Expected_and_Risk[10];
            //
            // but it didn't work

            Result.Name[i] = abc.Name[i];
            Result.Prop[i] = abc.Prop[i];
            Result.Forecast[i] = abc.Forecast[i];
            Result.AxB[i] = abc.Prop[i] * abc.Forecast[i];


            decimal a = Result.AxB[i];
            decimal sumAxB =+ a;

            double temp = (double)(a * a) ;
            Result.PowAxB[i] = (decimal)(temp);

        }

        return Convert.ToDecimal(Result); 
    }
}

}

推荐答案

更好的方法是将以下方法添加到Expected_and_Risk类中,并在构造函数中调用它.

Better way could be to add following method into Expected_and_Risk class and call it from within constructor.

编辑-完成编辑后将Initialize设为私有,然后在构造函数中调用它.

EDIT - edit is done to make Initialize private, and call it within constructor.

void Initialize(int size)
{
    Prop = new decimal[size];
    AxB = new decimal[size];
    Forecast = new decimal[size];
    PowAxB = new decimal[size];
    Name = new string[size];
}

    public Expected_and_Risk(int size)
    {
      ....
      Initialize(size);
    }

然后在ExpectValue中使用它,例如

After that use it in ExpectValue like

Expected_and_Risk Result = new Expected_and_Risk(size)// size is 10 in example;

这篇关于我无法创建包含对象内部属性数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆