C#强制开发人员在将值类型对象传递给方法之前对其进行初始化,不管是按值传递还是引用传递的实参都必须遵守这一规则。对于方法中的引用,编译器要求他作为参数传递给另一个方法前初始化为一个对象或者null值
public
class
Artical
{
public int Price = 0 ;
}
class Program
{
static void Main( string [] args)
{
int i = 10 ;
Artical articalA = null ;
Artical articalB = new Artical();
articalB.Price = 100 ;
fct(i, articalA, articalB);
Console.Write(articalA.Price); // 错误"未将对象引用设置到对象的实例"
Console.Write(articalB.Price); // 输出 10
}
static void fct( int i, Artical articalA, Artical articalB)
{
if (articalA == null )
{
articalA = new Artical();
}
articalA.Price = i;
articalB.Price = i;
}
}
{
public int Price = 0 ;
}
class Program
{
static void Main( string [] args)
{
int i = 10 ;
Artical articalA = null ;
Artical articalB = new Artical();
articalB.Price = 100 ;
fct(i, articalA, articalB);
Console.Write(articalA.Price); // 错误"未将对象引用设置到对象的实例"
Console.Write(articalB.Price); // 输出 10
}
static void fct( int i, Artical articalA, Artical articalB)
{
if (articalA == null )
{
articalA = new Artical();
}
articalA.Price = i;
articalB.Price = i;
}
}