从类中的方法返回对象

时间:2017-03-11 16:54:50

标签: c# object methods

我有一个由2个类组成的代码。在class Program里面有一个方法名calculate,它应该得到3个字符串并返回一个对象:

namespace ConsoleApplication1
{
    public class DataGridObject
    {
        public string MainName { get; set; }
        public double Level { get; set; }
        public double Exp { get; set; }
        public double AmountNeed { get; set; }
        public double TotalLose { get; set; }
        public double TotalGain { get; set; }
        public double TotalCost { get; set; }
        public Uri ImageSource { get; set; }

    }

   public static class Program
    {

            public object calculate(string db_name, string sheetname, string images_path)
            {

            string DataBase_File = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(),     String.Format("{0}",db_name));
            string SheetName = string.Format("{0}$",sheetname);
            string Images_File = string.Format(@"{0}",images_path);

            ***//some code in between which reads url, parsing json and do some math on the data in order to store it in `var d`//*** 

            var L = new List<DataGridObject>();

            string[] filePaths = Directory.GetFiles(Images_File);

            for (int z = 0; z < list_Exp.Count; z++)
              {
                var d = new DataGridObject();

                d.MainName = ...;
                d.Level = ...;
                d.Exp = ...;
                d.AmountNeed = ...;
                d.TotalLose = ...;
                d.TotalGain = ....;
                d.TotalCost = ....;
                d.ImageSource = new Uri....;

                L.Add(d);

              }

            return L;

          }


//calling the method:

    string db_name = "DataBase.xlsx";
    string sheetname = "sheet1";
    string images_path = "C:\\Users...";

    object a = calculate(db_name, sheetname, images_path);

}

我得到的错误是在我调用方法的行:

“字段初始值设定项不能引用非静态字段,方法或属性Program.db_name”,对其他2个字符串也是如此(Program.sheetname,Program.images_path)

1 个答案:

答案 0 :(得分:0)

主要问题是您的函数calculate是非static函数,您可能会尝试从static函数调用它。所以,请将您的功能更改为static,如下所示:

public static object calculate(string db_name, string sheetname, string images_path)

有关static字段和方法的详细信息,请查看this article