是否可以使用params关键字通过ref传递对象? [英] Is it possible to pass objects by ref with the params keyword?

查看:187
本文介绍了是否可以使用params关键字通过ref传递对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过ref 将很多参数传递给方法,但我不知道参数的数量.

I would like to pass a lot of arguments to a method by ref but I don't know the number of arguments.

我已经尝试过类似的方法,但是它不起作用:D:

I have tried something like this but is it not working :D :

public void myMethod(ref params object args)

我会考虑在params中传递指针,但是在C#中有点复杂:/

I will think to pass the pointers in params but is it little complicated in C# :/

可能的解决方法?

我想封装一部分代码,基本上是这样的:

I want to encapsulate a part of code, basically like this :

....

var collectionA = new List<string>();
var myObject = // an object
Optimizer.Optimize(ref collectionA, ref myObject); // cache
//{

MaClass.Treatment(); // use collectionA stored in cache via Optimizer

// the collectionA is modified in MaClass.Treatment()
...

//}
Optimizer.EndOptimize();
...

目标是,如果调用被封装到我的Optimizer中,则无法一直请求我的服务器接受相同的处理(HTTPRequest)

The goal, cannot request my server all the time for the same treatment (HTTPRequest) if the call was encapsulate into my Optimizer

推荐答案

否,这是不可能的.但是,您可以通过使方法中的数组发生变异,然后在调用位置从数组中读回值来获得很多的信息:

No, that's not possible. However, you can get much of the same by mutating the array in the method, then simply reading the values back out of the array at the call-site:

var args = new[] {x, y, z}
obj.myMethod(args);
x = args[0];
y = args[1];
z = args[2];

(可以简单地泛化为仅在运行时才知道的许多参数)

(which can be trivially generalized to a number of arguments known only at runtime)

这篇关于是否可以使用params关键字通过ref传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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