简体   繁体   English

C#out参数值传递

[英]C# out parameter value passing

I am using contactsreader.dll to import my Gmail contacts. 我正在使用contactsreader.dll导入我的Gmail联系人。 One of my method has the out parameter. 我的一个方法有out参数。 I am doing this: 我这样做:

Gmail gm = new Gmail();
DataTable dt = new DataTable();
string strerr;
gm.GetContacts("chendur.pandiya@gmail.com", "******", true, dt, strerr);
// It gives invalid arguments error..

And my Gmail class has 我的Gmail课程有

public void GetContacts(string strUserName, string strPassword,out bool boolIsOK,
out DataTable dtContatct, out string strError);

Am I passing the correct values for out parameters? 我是否为out参数传递了正确的值?

You need to pass them as declared variables, with the out keyword: 您需要使用out关键字将它们作为声明的变量传递:

bool isOk;
DataTable dtContact;
string strError;
gm.GetContacts("chendur.pandiya@gmail.com", "******",
    out isOk, out dtContact, out strError);

In other words, you don't pass values to these parameters, they receive them on the way out . 换句话说,您不会将值传递给这些参数,而是在出路out接收它们。 One way only. 只有一种方法。

You have to put "out" when calling the method - gm.GetContacts("chendur.pandiya@gmail.com", "******", out yourOK, out dt, out strerr); 调用方法时你必须把“out” - gm.GetContacts("chendur.pandiya@gmail.com", "******", out yourOK, out dt, out strerr);

And by the way, you don't have to do DataTable dt = new DataTable(); 顺便说一下,你不必做DataTable dt = new DataTable(); before calling. 在打电话之前 The idea is that the GetContacts method will initialize your out variables. 我们的想法是GetContacts方法将初始化你的out变量。

Link to MSDN tutorial. 链接MSDN教程。

Since the definition of your function 既然定义了你的功能

public void GetContacts(string strUserName, string strPassword, out bool boolIsOK, out DataTable dtContatct, out string strError);

requires that you pass some out parameters, you need to respect the method signature when invoking it 要求您传递一些out参数,您需要在调用时尊重方法签名

gm.GetContacts("<username>", "<password>", out boolIsOK, out dtContatct, out strError);

Note that out parameters are just placeholders, so you don't need to provide a value before passing them to the method. 请注意, out参数只是占位符,因此在将它们传递给方法之前不需要提供值。 You can find more information about out parameters on the MSDN website . 您可以在MSDN网站上找到有关out参数的更多信息。

I would suggest that you pass a bool variable instead of a literal value and place the out keyword before them. 我建议您传递bool变量而不是文字值,并将out关键字放在它们之前。

bool boolIsOK = true;
gm.GetContacts("chendur.pandiya@gmail.com", "******", out boolIsOK, out dt, out strerr)

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

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