从另一个类更改类的属性

时间:2014-01-08 21:02:38

标签: c# .net

我有一个属性类:

public class TaskConfiguration 
{
    public string Task_Name
    {
        get; set;
    }

    public string task_id
    {
        get; set;
    }
}

在代码的某处,我有一个方法可以在程序执行的早期设置类的属性:

public class TaskManagingProcess
{
    public void InsertTaskProperties()
    {
        TaskConfiguration tc = new TaskConfiguration();
        tc.Task_Name = "Sample Task";
        tc.task_id = "1";
    }
}

稍后在执行中,在另一个类中,我想修改TaskConfiguration类的属性,但我不确定如何。如果我使用以下内容,它将无法工作,因为它会创建TaskConfiguration类的新实例。

TaskManagingProcess tmp = new TaskManagingProcess;
tmp.InsertTaskProperties();

那我怎么能这样做呢?

2 个答案:

答案 0 :(得分:4)

您想传递对象:

public void InsertTaskProperties(TaskConfiguration config) {
    config.Task_Name = "Sample Task";
    config.task_id = "1";
}

然后:

TaskManagingProcess tmp = new TaskManagingProcess();
TaskConfiguration config = new TaskConfiguration();

tmp.InsertTaskProperties(config);

(我对你的代码做了一个非常大的假设..但这应该给你基本的想法)

答案 1 :(得分:1)

在我看来,TaskManagingProcess是一个代理类,这就是我推荐的原因:

 public class TaskConfiguration 
    {
        public string Task_Name
        {
            get;
            set;
        }

        public string task_id
        {
            get;
            set;
        }
    }


public class TaskManagingProcess
{
    private TaskConfiguration taskConfiguration;

    public TaskManagingProcess(TaskConfiguration taskConfiguration)
    {
        this.taskConfiguration = taskConfiguration;
    }

    public void InsertTaskProperties(string taskId, string name)
    {
        taskConfiguration.task_id = taskId;
        taskConfiguration.Task_Name = name;         
    }
}

所以最后你可以这样做(见下文)并轻松添加代码来处理TaskConfiguration对象的访问:

TaskConfiguration taskConfiguration = new TaskConfiguration() { task_id = "1", Task_Name = "Sample Task" };
TaskManagingProcess taskManaginProcess = new TaskManagingProcess(taskConfiguration);

taskManaginProcess.InsertTaskProperties("2", "Sample Task 2");
相关问题