简体   繁体   中英

How to add object from a class to List in another class.

I am not sure I am asking this question properly and have had trouble searching for what I need in this case. I have two classes. One consists of three items that I will assign.

namespace Common.PriceFeed
{
    public class SurchargeSKUList
    {
        public string WebSKUID { get; set; }
        public decimal AdditionalPrice { get; set; }
        public string Currency { get; set; }
    }
}

The other class is a list containing the items from the above class.

namespace Common.PriceFeed
{
    public class BaseSurcharge
    {
        public List<SurchargeSKUList> SKUList { get; set; }
    }
}

My problem is, then I try to use BaseSurcharge, I get errors like I am using as type as a variable or that I "cannot implicitly convert type..." My .net code is below.

Thank you.

if (BaseSurcharges.Rows.Count > 0)
{
    foreach (DataRow row in BaseSurcharges.Rows)
    {
        SurchargeSKUList newSKUList = new SurchargeSKUList();
        newSKUList.WebSKUID = row["WebSKUID"].ToString();
        newSKUList.AdditionalPrice = Convert.ToDecimal(row["AdditionalPrice"]);
        newSKUList.Currency = row["Currency"].ToString();

        BaseSurcharge newSurcharge = new BaseSurcharge();
        newSurcharge.SKUList = List<SurchargeSKUList>newSKUList;

        //BaseSurcharge List<SurchargeSKUList> newSurcharge = new BaseSurcharge
        //BaseSurcharge newSurcharge = new BaseSurcharge();
        //newSurcharge.SKUList = newSKUList;
            }
        }
newSurcharge.SKUList = List<SurchargeSKUList>newSKUList;

should be changed to:

newSurcharge.SKUList = new List<SurchargeSKUList>();
newSurcharge.SKUList.Add(newSKUList);

I didn't check this out on Visual Studio. So it might have some syntax errors.

But better yet - BaseSurcharge should have SKUList = new List<SurchargeSKUList>(); in its constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM