C#如何看待整型像他们阵? [英] C# how to treat ints like they are array?

查看:89
本文介绍了C#如何看待整型像他们阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有5 INT的这是不是一个数组中!并想改变他们都在1环。 ?有没有什么办法让一个数组,这将让那些5号的值,并可能直接改变他们



是这样的:

  int类型的= 10; 
INT B = 20;

INT [] =蕾哈娜// ....?

为(int类型的= 0; A< rihanna.length; A ++)
蕾哈娜[A] ++;

Console.WriteLine({0} {1},A,B)//我想在这里看到的是11和21


解决方案

我觉得这是解决这个问题,如果你放松要求的一种方式 - 有实体的阵列,将不允许修改的设置通过对数组操作本地 INT 变量。



要做到这一点,可以捕捉在该变量的引用数组代表每个采取 REF INT VAL 的。

 无效增(REF INT X)
{
X ++;
}
无效设置(REF INT X,INT金额)
{
X =金额;
}

样品无效()
{
INT A = 10;
INT B = 20;

//的增加变量代表
变种increaseElements =新的操作[] {
()=>阵列;增加(REF一),
()=>增加(REF B)
};
increaseElements [0](); //电话委托,不幸的是(),而不是++
Console.WriteLine(一); //写11

//现在用的设置变量代表数组:
变种setElements =新动作< INT> [] {
V =>设置(REF A,V),
)(V =>设置(REF B,V)
};
setElements [0](3);
Console.WriteLine(一); //写3
}






  • 直接使用委托你必须给他们打电话有()。

  • 有可能解决()而不是 ++ 问题通过包装委托到一个对象,将调用随着其 ++ 实施....

  • 设置版本问题,其中一个需要调用(3),而不是 = 3 将需要更多的挂羊头卖狗肉 - 实现自定义类索引重定向设置[索引] 调用保存的setter函数



警告:这是真正为娱乐目的而进行的 - 请不要尝试在真正的代码<。 / p>

Let's say I have 5 int's which are not an array! and I want to change them all in 1 loop. Is there any way to make an array which will get the values of those 5 numbers and could change them directly?

Something like:

int a = 10;
int b = 20;

int[] rihanna = // .... ? 

for(int a=0; a<rihanna.length;a++)
    rihanna[a]++;

Console.WriteLine("{0} {1} ",a,b) // what I want to see here is 11 and 21

解决方案

I think there is a way to solve it if you relax requirement - have array of entities that would allow modifying set of local int variables via operations on array.

To do so it is possible to capture references to the variables in an array of delegates that each take ref int val.

void Increase(ref int x) 
{
    x++;
}
void Set(ref int x, int amount) 
{
    x = amount;
}

void Sample()
{
  int a = 10;
  int b = 20;

  // Array of "increase variable" delegates
  var increaseElements = new Action[] { 
    () =>  Increase(ref a), 
    () =>  Increase(ref b) 
  };
  increaseElements[0](); // call delegate, unfortunately () instead of ++ 
  Console.WriteLine(a); // writes 11

  // And now with array of "set the variable" delegates:
  var setElements = new Action<int>[] { 
    v =>  Set(ref a,v), 
    v =>  Set(ref b,v) 
  };
  setElements[0](3); 
  Console.WriteLine(a); // writes 3 
}

Notes

  • directly using delegates you have to call them with ().
  • it may be possible to fix () instead of ++ issue by wrapping delegate into an object that will call Increase as its ++ implementation....
  • Issue with Set version where one need to call (3) instead of = 3 will require more trickery - implementing custom class with indexing to redirect set [index] to call saved setter function.

Warning: This is really done for entertainment purposes - please don't try it in real code.

这篇关于C#如何看待整型像他们阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆