Skip to content

Instantly share code, notes, and snippets.

@knknkn1162
Last active November 21, 2016 06:26
Show Gist options
  • Save knknkn1162/b5473a839c5d7e64b5c9c0f1fb6ae0ca to your computer and use it in GitHub Desktop.
Save knknkn1162/b5473a839c5d7e64b5c9c0f1fb6ae0ca to your computer and use it in GitHub Desktop.
C#における参照型と値型のはまりどころ ref: http://qiita.com/knknkn1162/items/aa088d4cc22f25c893fb
static void Main(string[] args)
{
int i = 1;
int j = i; //iの値が複製されて、jに格納される(intは値型)
j = j + 1;
List<int> arr = new List<int>{ 1, 2, 3 };
Console.WriteLine("{0} {1}", i, j); //1 2
var newArr = arr; // List<int>は参照型なので、値自体ではなく、値のアドレスが複製される。
newArr[0] = 10; //arrの参照情報とnewArrの参照情報は同じなので、arr[0]も変更される
arr.ForEach(c => Console.WriteLine(c)); //10 2 3
}
//[&i]の&は参照キャプチャ. [=i]と書けば、iの値を複製することになる
func[i] = [&i](int c) -> int { return c * i; };
static void Main(string[] args)
{
var dic = new Dictionary<string, int>() {
{"key0", 1},
{"key1", 3}
};
var newDic = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> pair in dic)
{
//実はKeyValuePair<T,U>は参照型。
KeyValuePair<string, int> newPair = pair;
newDic.Add(newPair.Key, newPair.Value*2);
}
//Key: key0, Value: 2
//Key: key1, Value: 6
newDic.ToList().ForEach(c => Console.WriteLine("Key : {0}, Value : {1}", c.Key, c.Value));
}
//[&i]の&は参照キャプチャ. [=i]と書けば、iの値を複製することになる
func[i] = [&i](int c) -> int { return c * i; };
static void Main(string[] args)
{
int num = 10;
var func = new Func<int, int>[num];
for(int i = 0; i < num; i++)
{
func[i] = c => c*i; //i は自由変数
}
//ラムダ式中のiは値でなく参照。なので、キャプチャごとに複製されず、参照される!
//なので、func[5]中のi = 10となる。
Console.WriteLine(func[5](3)); //30
//foreachに関しては、動作が変更された。
foreach(var i in Enumerable.Range(0,num))
{
func[i] = c => c*i;
}
//3 * 5で直感通りの結果になる
Console.WriteLine(func[5](3)); //15
}
static void Main(string[] args)
{
int num = 10;
var func = new Func<int, int>[num];
for(int i = 0; i < num; i++)
{
func[i] = c => c*i; //i は自由変数
}
//ラムダ式中のiは値でなく参照。なので、キャプチャごとに複製されず、参照される!
//なので、func[5]中のi = 10となる。
Console.WriteLine(func[5](3)); //30
//foreachに関しては、動作が変更された。
foreach(var i in Enumerable.Range(0,num))
{
func[i] = c => c*i;
}
//3 * 5で直感通りの結果になる
Console.WriteLine(func[5](3)); //15
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment