将属性作为“输出”传递; C# 中的参数
假设我有:
public class Bob
{
public int Value { get; set; }
}
我想将 Value 成员作为输出参数传递,
Int32.TryParse("123", out bob.Value);
但我收到编译错误,“'out'参数未分类为变量。”有什么办法可以实现这一点,或者我必须提取一个变量,à la:
int value;
Int32.TryParse("123", out value);
bob.Value = value;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须显式使用字段和“普通”属性,而不是自动实现的属性:
然后您可以将字段作为输出参数传递:
但是,当然,这只在同一类,因为该字段是私有的(并且应该是!)。
属性只是不允许你这样做。即使在 VB 中,您可以通过引用传递属性或将其用作输出参数,但基本上还是有一个额外的临时变量。
如果您不关心
TryParse
的返回值,您始终可以编写自己的辅助方法:然后使用:
这样您就可以使用单个临时变量,即使您需要在多个中执行此操作地方。
You'd have to explicitly use a field and "normal" property instead of an auto-implemented property:
Then you can pass the field as an out parameter:
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:Then use:
That way you can use a single temporary variable even if you need to do this in multiple places.
你可以实现这一目标,但不能通过财产实现。
您不能在
Value
上使用out
,但可以在AnotherValue
上使用。这会起作用
,但是,通用准则告诉您不要将类字段公开。所以你应该使用临时变量方法。
You can achieve that, but not with a property.
You cannot use
out
onValue
, but you can onAnotherValue
.This will work
But, common guidelines tells you not to make a class field public. So you should use the temporary variable approach.