using System;
using System.Data;
using System.Collections;public class MyClass
{
public static void Main()
{
DataTable tb = new DataTable();
SetTableNull(tb);
string result = string.Empty;
if ( tb == null )
{
result = "DataTable is null";
}
else
{
result = "DataTable is not null";
}
Console.WriteLine(result);
Console.ReadLine();
}
public static void SetTableNull(DataTable dt)
{
dt = null;
}
}
以上这段代码,为什么SetTableNull函数始终没有发挥作用?引用类型传递的对象在其它函数中重新做譬如实例化或者付空的时候为什么会出现这样的结果?请麻烦讲讲
using System.Data;
using System.Collections;public class MyClass
{
public static void Main()
{
DataTable tb = new DataTable();
SetTableNull(tb);
string result = string.Empty;
if ( tb == null )
{
result = "DataTable is null";
}
else
{
result = "DataTable is not null";
}
Console.WriteLine(result);
Console.ReadLine();
}
public static void SetTableNull(DataTable dt)
{
dt = null;
}
}
以上这段代码,为什么SetTableNull函数始终没有发挥作用?引用类型传递的对象在其它函数中重新做譬如实例化或者付空的时候为什么会出现这样的结果?请麻烦讲讲
用引用的..改:----------------------------------------SetTableNull(ref tb);public static void SetTableNull(ref DataTable dt)
{
dt = null;
}
这属于传值和传址的差别.
public static void SetTableNull(DataTable dt)这里的 dt 只在 SetTableNull 方法里产生作用。DataTable tb = new DataTable();这里的 dt 在 Main 方法里产生作用。你如果想在 SetTableNull 方法里设置 DataTable tb = new DataTable(); 的 dt 的值的话。1.
public static void SetTableNull(ref DataTable dt)
{
dt = null;
}调用:
DataTable tb = new DataTable();
SetTableNull(ref tb);或者 2.public static DataTable SetTableNull(DataTable dt)
{
dt = null;
return dt;
}
调用:
DataTable tb = new DataTable();
tb = SetTableNull(tb);
.Net中有值类型和引用类型两种对象,DataTable属于引用类型的变量,这种变量的传递本身就是引用传递的,而不是上面各位说的传递的是副本。下面看这段代码,为了简化,把DataTable换成了TextBox对象,都是引用类型的,说明的是同样的问题
using System;
using System.Windows.Forms;
using System.Collections;public class MyClass
{
public static void Main()
{
TextBox tb = new TextBox();
tb.Text = "OldValue";
SetNewValue(tb);
string currentTbText = tb.Text;
Console.WriteLine(currentTbText);
Console.ReadLine();
}
public static void SetNewValue(TextBox tb)
{
//part1
tb.Text = "NewValue"; //part2
// tb = new TextBox();
// tb.Text = "NewValue";
//part3
// TextBox otherTb = new TextBox();
// otherTb.Text = "OtherValue";
// tb = otherTb;
//part4
// tb = null;
}
}
首先运行的是Part1部分的代码,楼上各位有没有发现,即使不使用ref关键字传递参数,传递的对象的Text属性仍然发生了变化,即起到了ref引用传递的效果。
但是大家注释掉Part1,使用Part2,Part3甚至Part4的时候,也就是我在顶楼描述的 "重新做譬如实例化或者付空"这种情况,传入的对象就没有发生Part1代码中的效果。其实我想问的是这之间的差异是怎么造成的?欢迎楼上的各位继续参加讨论,顺便也强化下基础概念。
值传递.
清清楚楚
请指出问题的关键,谢谢!
public static void SetTableNull(DataTable dt)
{
dt = null;
}上面的dt是重新申请的一个指向的Main()中dt的一个地址当dt=null时,那就只是新申请的这个dt指向null,原来的dt指向不变;当赋值时,因为dt指向原来的dt那就是给原来的dt赋值,这样原来的dt也就变了
http://www.webjx.com/htmldata/2005-08-27/1125096594.html
欢迊来到麦高网-私活兼职首选平台 www.mgao.net
商店开好之后如果路人来问A路标指向的那个地方有商店吗?你会毫不犹豫的说:那肯定有了!