在 C# 中将属性作为“输出"参数传递 [英] Passing a property as an 'out' parameter in C#

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

问题描述

假设我有:

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

我想将 Value 成员作为输出参数传递,例如

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

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

但是我得到一个编译错误,'out' 参数不被归类为变量." 有没有办法实现这一点,或者我将不得不提取一个变量,à拉:

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!).

属性只是不允许您这样做.即使在您可以通过引用传递属性或将其用作输出参数的 VB 中,基本上也有一个额外的临时变量.

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.

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

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;
}

然后使用:

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天全站免登陆