c# 变量

2019-07-13  本文已影响0人  柒轩轩轩轩

stack vs heap

Stack(

Heap

内存

GC

static

Parameters & Arguments

image.png

arguments 为值传递

static void Main()
{
   int x = 8;
   Foo(x); //Make a copy of x
   Console.WriteLine(x);// x will still be 8
}
static void Foo(int p)
{
  p = p+1;
  Console.WriteLine(p); // 9
}

按值传递引用类型的arguments

static void Main() 
{
  StringBuilder sb = new StringBuilder();
  Foo(sb);
  Console.WriteLine(sb.ToString());//test
}

static void Foo(StringBuilder fooSB)
{
  fooSB.Append("test");
  fooSB = null;
}
static void Main()
{
   int x = 8;
   Foo(ref x); //Make a copy of x
   Console.WriteLine(x);// 9
}
static void Foo(int p)
{
  p = p+1;
  Console.WriteLine(p); // 9
}
static void Split(string name, out string firstName, out string lastName)
{
int i = name.LastIndexof(' ');
firstNames = name.Substring(0,i);
lastNames = name.Substring(i+1);
}

static void main(){
{
Split("Stevie Ray Vaughan", out string a, out string b);
Console.WriteLine(a);// Stevie Ray
Console.WriteLine(b);// Vaughan
}

按引用类型进行传递的含义

当你按引用传递arguments的时候,相当于给现有变量的存储位置起了个别名,而不是创建了一个新的存储位置

params 修饰符

static int Sum(params int[] ints)
{
 int sum = 0;
for (int i =0; i< ints.Length; i++)
{
sum += ints[i];
}
return sum;
}
static void Main()
{
int total = Sum(1,2,3,4);
// int total = Sum(new int[] {1,2,3,4});
Console.WriteLine(total);//10
}

ref locals

int [] nubmers = {0, 1, 2, 3, 4 }
ref int numRef = ref numbers[2];
numRef * = 10;
Console.WriteLine(numRef); //20
Console.WriteLine(numbers[2]); //20
上一篇 下一篇

猜你喜欢

热点阅读