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

前端 未结 2 1373
渐次进展
渐次进展 2020-12-05 09:16

Suppose I have:

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

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

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 09:38

    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.

提交回复
热议问题