本文介绍了通过引用传递类对象(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我需要通过引用另一个类中的方法

来传递一个类对象(this)。当我执行以下代码时,我得到错误(不能

传递''< this>''作为ref或out参数,因为它是只读的)..是否有

任何方式制作< this>不是只读的?


我简化了以下代码。有一个Task类和一个Data

类。我试图通过ref将任务类传递给数据类。


公共类任务

{

public Task( int taskId)

{

TaskData data = new TaskData();

data.GetTaskFromId(ref taskId);

data.Close();

}

}


公共类TaskData

{

public void GetTaskFromId(ref Task task)

{

SqlCommand cmd = new SqlCommand(" sp_Task_GetByID_Select",conn);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter(" @ TaskID",task.TaskId));


SqlDataReader reader = cmd.ExecuteReader();

while(reader.Read())

{

task.Name = reader [" Name"]。ToString();

task.Description = reader [" Descr"]。ToString();

}


reader.Close();

cmd.Dispose();


}

}


所有的建议都是适用的。


谢谢!


-

Jay Douglas

Fort Collins,CO

Hello, I am needing to pass a class object (this) by reference to a method
in a different class. When I do the following code I get the error (Cannot
pass ''<this>'' as a ref or out argument because it is read-only) .. Is there
any way to make <this> not read-only?

I have simplified the following code. There is a Task class and a Data
Class. I am trying to pass the task class by ref to the data class.

public class Task
{
public Task(int taskId)
{
TaskData data = new TaskData();
data.GetTaskFromId(ref taskId);
data.Close();
}
}

public class TaskData
{
public void GetTaskFromId(ref Task task)
{
SqlCommand cmd = new SqlCommand("sp_Task_GetByID_Select", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@TaskID", task.TaskId));

SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
task.Name = reader["Name"].ToString();
task.Description = reader["Descr"].ToString();
}

reader.Close();
cmd.Dispose();

}
}

All suggestions are appreicated.

Thanks!

--
Jay Douglas
Fort Collins, CO


推荐答案




(不能








我没看到*为什么*你试图通过引用传递它在第一个

的地方 - 你能解释一下吗?


你*可能*误解了参考的传递参数真的是

关于。请参阅



-

Jon Skeet - < sk *** @ pobox.com>


如果回复该团体,请不要给我发邮件



I don''t see *why* you''re trying to pass it by reference in the first
place - could you explain?

You *may* misunderstand what passing parameters by reference is really
about. See
http://www.pobox.com/~skeet/csharp/parameters.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


这篇关于通过引用传递类对象(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 17:25