简体   繁体   English

如何在 function 中创建一个与传递给 C# 中的 function 的参数名称相同的新变量?

[英]How to create a new variable in a function with the same name of a parameter passed to that function in C#?

It's easier if I just state that in this:如果我只是 state 会更容易:

public static void GetObstacles(params string[] ObstacleLayers)
{
    foreach (string Layer in ObstacleLayers)
    {
        var Layer = _tiledMap.GetLayer<TiledMapTileLayer>(Layer);
    }
}

I want the created variable var Layer to be named after the string Layer .我希望创建的变量var Layerstring Layer命名。

The thing you ask for is as if you were asking for designate a cat as a dog the same time like in a schrodinger box.您要求的事情就像您要求将猫指定为狗一样,就像在薛定谔盒中一样。

However, you have the notion of dynamic but this does not apply to foreach because you can't assign the iteratored var and here the goal is not to modulate it.但是,您有动态的概念,但这不适用于foreach ,因为您无法分配迭代的 var,而这里的目标不是调整它。

Therefore you need to write:因此,您需要编写:

foreach (string layerName in ObstacleLayers)
{
  var layer = _tiledMap.GetLayer<TiledMapTileLayer>(layerName);
  // do something with the layer
}

So the string element you iterate over from the collection is used to get an object instance of type Layer (perhaps) to work on.因此,您从集合中迭代的字符串元素用于获取要处理的Layer类型的 object 实例。

It seems that you did not understand or learned what are loops and variables and their usage as well as scope .您似乎不了解或不了解什么是循环变量及其用法以及scope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM