读书人

引用的疑惑,该如何处理

发布时间: 2012-01-29 21:39:32 作者: rapoo

引用的疑惑
看到引用这部分时,遇到一些问题,请高手耐心解答,如果学的好帮忙讲下函数前的static修饰符什么时候该用,请看一下3个小程序,任意回答一个也有分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
string s;

void Fn(ref string a, ref string b)
{
s = "one";
a = "two";
b = "three";
Console.WriteLine("{0} {1} {2}", s, a, b);
}
void G()
{
a1.Fn(ref s, ref s);
}
static void Main(string[] args)
{
Program a1 = new Program();
a1.G();

}
}
} // 正确 输出 three three three
------------------------------------------------------------
现在对上面的程序稍作修改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
string s;

void Fn(ref string a, ref string b)
{
s = "one";
a = "two";
b = "three";
Console.WriteLine("{0} {1} {2}", s, a, b);
}
/*void G()
{
a1.Fn(ref s, ref s);
}*/
static void Main(string[] args)
{
Program a1 = new Program();
a1.Fn();

}
}
} //错误 为什么?????????? Error1An object reference is required for the non-static field, method, or property 'ConsoleApplication2.Program.s'
-----------------------------------------
书上说 “在作为引用参数传递之前,实际参数必须明确赋值”
为什么第一个程序中的string s没有明确赋值也正确???
而下面这个对整数的引用没明确赋值却错了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{

static void Fn(ref int a, ref int b) //不用static也要错,什么时候用??????
{
a = 1;
b = 5;
}

static void Main(string[] args)
{
int x;
int y; //没有明确赋值
Fn(ref x, ref y);
}
}
}
Error1Use of unassigned local variable 'x'
Error2Use of unassigned local variable 'y'

[解决办法]
不用static也要错,什么时候用?????? Fn(ref x, ref y); 如果不是static方法,就不能在static方法里面直接调用,必须通过实例调用

[解决办法]
For 2

void Fn(ref string a, ref string b)

You can't use a1.Fn(); need be a1.Fn(ref s, ref s);

“在作为引用参数传递之前,实际参数必须明确赋值”

Just for value type, string is reference type

//不用static也要错,什么时候用??????

Because your main function use static (static void Main)

[解决办法]
另外,实际项目中绝对要禁止 a1.Fn(ref s, ref s); 这种写法

[解决办法]
类的字段成员有默认值,而在方法内部的临时变量没有默认值,必须初始化赋值


[解决办法]
ref是要先赋值在使用
你这情况可以用out
但是在接受参数的方法中,在退出前要给参数赋值

static是静态方法。静态方法中调用非静态方法需要先实例化

读书人网 >C#

热点推荐