【问题标题】:HowTo: Return an object from a (static) method?如何:从(静态)方法返回对象?
【发布时间】:2014-09-16 09:14:24
【问题描述】:

我正在使用 C# 2.0 为 Job Scheduler 构建一个 WinForms 应用程序。

Program.cs 中写了一个public class Job,定义了Job object

//Class for defining Job object and its properties 
public class Job
{
    private int IntJobID;
    public int JobID
    {
        get {return IntJobID;}
        set {IntJobID = value;}
    }
    private string StrJobName;
    public string JobName
    {
        get { return StrJobName; }
        set { StrJobName = value; }
    }
    //Several other properties defined here. 
}

还在Program.cs 中写了一个public static class ApplicationName,用于包含应用程序范围的配置变量和所有辅助方法。

//Static Class for Global Properties and Global Methods 
//*****************************************************
public static class ApplicationName
{
    //Global Properties 
    //***************************
    public static string ConfigFilePath = "D:\\ApplicationName\\conf\\ApplicationName.ini"; 
    public static string DBFilePath = "D:\\ApplicationName\\data\\ApplicationName.xml"; 
    //Global Methods 
    //************************
    public static void HelperMethod1(Args)
    {
    }
    public static string HelperMethod2(Args)
    {
    }
    public static Job GetJobByID(int JobID)
    {
        XmlDocument XMLDB = new XmlDocument(); XMLDB.Load(DBFilePath);
        Job ObjJob = new Job();
        ObjJob.JobName = XMLDB.SelectSingleNode("/ApplicationName/Job[JobID=" + JobID.ToString() + "]/JobName").InnerText.Trim();
        //Several other properties are retrieved from the DB and set to the object here. 
        return ObjJob;
    }

}

public static class ApplicationName 中的一个辅助方法 GetJobByID 需要创建/实例化 Job 对象并返回相同的对象。我相信这是可能的,ClassA 中的一个方法创建并返回ClassB 的实例/对象。

注意:此方法适用于从其他表单如Form1.cs、Form2.cs等通过以下方式访问。据我所知,这也是允许的并且是公认的做法。

private void FormAddEditJob_Load(object sender, EventArgs e)
{
    int SelectedJobID = Convert.ToInt32(this.Tag);
    //Creating an instance of the Job Class 
    //Assigning the value of the Job object returned by GetJobByID method 
    Job JobToEdit = ApplicationName.GetJobByID(SelectedJobID);
    TextBoxJobID.Text = SelectedJobID.ToString();
    TextBoxJobName.Text = JobToEdit.JobName; 
}

问题:GetJobByID 方法返回的object 未存储在对象引用JobToEdit 中。甚至可能GetJobByID 方法没有正确/按预期返回对象。我在这里做错了什么?这不是返回对象的正确方法吗?

【问题讨论】:

  • 你的代码基本上没有问题,除了不需要初始化JobToEdit,你可以这样做:Job JobToEdit = MedImmuneBJM.GetJobByID(SelectedJobID);
  • 什么是MedImmuneBJM?你不应该用ApplicationName.GetJobByID(SelectedJobID) 调用它吗?
  • @DionV.:是的,抱歉打错了。我已经编辑了静态类名。
  • “对象未存储在JobToEdit”是什么意思?是null吗?您是否检查过OldJob 确实包含您在GetJobById 中返回它时所期望的内容?
  • 哦好的,是null。在调试器中检查您的静态方法是否返回了正确的对象实例。

标签: c# winforms oop


【解决方案1】:

发现并解决了问题。

GetJobByID 方法中的一条语句 ObjJob.PropertyName = XMLDB.SelectSingleNode() 抛出异常,原因是从 DB 获取空值,从而导致 ObjJob 对象作为空值返回。通过逐行调试发现这一点。

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2012-05-13
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多