传递一个属性作为在C#中的“出”参数 [英] Passing a property as an 'out' parameter in C#

查看:147
本文介绍了传递一个属性作为在C#中的“出”参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

 公共类鲍勃
{
    公共int值{搞定;组; }
}

我要到的的成员通过像

out参数

  Int32.TryParse(123,出bob.Value);

但我得到一个编译错误,的'出'参数不属于变量。的有没有办法做到这一点,还是我将不得不提取变量, LA:

  int值;
Int32.TryParse(123,超时值);
bob.Value =价值;


解决方案

您不得不明确地使用字段和正常的属性,而不是自动实现的属性:

 公共类鲍勃
{
    私人int值;
    公众诠释的价值
    {
        {返回值; }
        集合{THIS.VALUE =价值; }
    }
}

然后就可以通过的字段的作为out参数:

  Int32.TryParse(123,出bob.value);

不过,当然,这只会在同一个类中工作,因为该领域是私有的(也应该!)。

属性只是没有让你这样做。即使在VB中,你的可以的按引用传递一个属性或使用它作为一个输出参数,但基本上是一个额外的临时变量。

如果你不关心的TryParse 的返回值,你总是可以编写自己的辅助方法:

 静态INT ParseOrDefault(字符串文本)
{
    INT TMP;
    int.TryParse(文字,出TMP);
    返回TMP;
}

然后使用:

  bob.Value = Int32Helper.ParseOrDefault(123);

这样,即使你需要这样做在多个地方,你可以使用一个临时变量。

Suppose I have:

public class Bob
{
    public int Value { get; set; }
}

I want to pass the Value member as an out parameter like

Int32.TryParse("123", out bob.Value);

but I get a compilation error, "'out' argument is not classified as a variable." Is there any way to achieve this, or am I going to have to extract a variable, à la:

int value;
Int32.TryParse("123", out value);
bob.Value = value;

解决方案

You'd have to explicitly use a field and "normal" property instead of an auto-implemented property:

public class Bob
{
    private int value;
    public int Value
    { 
        get { return value; } 
        set { this.value = value; }
    }
}

Then you can pass the field as an out parameter:

Int32.TryParse("123", out bob.value);

But of course, that will only work within the same class, as the field is private (and should be!).

Properties just don't let you do this. Even in VB where you can pass a property by reference or use it as an out parameter, there's basically an extra temporary variable.

If you didn't care about the return value of TryParse, you could always write your own helper method:

static int ParseOrDefault(string text)
{
    int tmp;
    int.TryParse(text, out tmp);
    return tmp;
}

Then use:

bob.Value = Int32Helper.ParseOrDefault("123");

That way you can use a single temporary variable even if you need to do this in multiple places.

这篇关于传递一个属性作为在C#中的“出”参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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