在 C# 中将属性作为“输出”参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1370238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:46:28  来源:igfitidea点击:

Passing a property as an 'out' parameter in C#

c#propertiesout-parameters

提问by thorncp

Suppose I have:

假设我有:

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

I want to pass the Valuemember as an out parameter like

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

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:

但我收到编译错误,“'out' 参数未归类为变量。” 有没有办法实现这一点,或者我将不得不提取一个变量,à la:

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

采纳答案by Jon Skeet

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 fieldas 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 canpass a property by reference or use it as an out parameter, there's basically an extra temporary variable.

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

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

如果您不关心 的返回值TryParse,您可以随时编写自己的辅助方法:

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.

这样,即使您需要在多个地方执行此操作,您也可以使用单个临时变量。

回答by Pierre-Alain Vigeant

You can achieve that, but not with a property.

您可以实现这一点,但不能通过属性实现。

public class Bob {
    public int Value { get; set; } // This is a property

    public int AnotherValue; // This is a field
}

You cannot use outon Value, but you can on AnotherValue.

您不能使用outon Value,但可以使用 on AnotherValue

This will work

这将工作

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

But, common guidelines tells you not to make a class field public. So you should use the temporary variable approach.

但是,通用指南告诉您不要公开类字段。所以你应该使用临时变量方法。