【问题标题】:Why can fields be used as out/ref parameters and not properties? [duplicate]为什么字段可以用作 out/ref 参数而不是属性? [复制]
【发布时间】:2014-01-07 02:54:42
【问题描述】:

当我们将 Fields 作为 out/ref 参数传递时,属性和 Fields 的不同之处。两者的区别是内存分配吗?

【问题讨论】:

标签: c# oop properties


【解决方案1】:

属性根本不像字段,它们就像方法。

这是一个字段;它没有任何逻辑。

private int _afield;

这是一个定义 getter 和 setter 的属性。
getter 和 setter 是方法。

public int AField
{
    get
    {
        return _aField;
    }
    set
    {
        _aField = value;
    }
}

这是默认属性。
它和之前的属性和字段完全一样,只是它为你做了很多工作

public int BField { get; set; }

【讨论】:

  • 它们不仅仅是方法,它们是方法!编译器在内部为您的属性 getter 和 setter 创建了两个方法(int get_AField()void set_AField(int value))。而且您不能对函数结果完全执行ref
  • 您的所有解释似乎都是正确的。请注意,严格来说,这不是它们不能用于refout 参数的原因 - 可以很好地定义语言,以便将对相应参数的任何访问转换为适当的方法调用为财产。
【解决方案2】:

最大的区别是属性或索引器不能作为refout 参数(demo)传递。

这是因为属性不一定有后备存储 - 例如,可以动态计算属性。

由于传递outref 参数需要获取变量在内存中的位置,并且由于属性缺少该位置,因此该语言禁止将属性作为ref/out 参数传递。

【讨论】:

  • 谢谢..总结得很好
【解决方案3】:

描述属性的最佳方式是用“getter”和“setter”方法的习惯用法。

当你访问一个属性时,你实际上是在调用一个“get”方法。

Java

private int _myField;

public int getMyProperty()
{
    return _myField;
}

public int setMyProperty(int value)
{
    _myField = value;
}

int x = getMyProperty(); // Obviously cannot be marked as "out" or "ref"

C#

private int _myField;
public int MyProperty
{
    get{return _myField;}
    set{_myField = value;}
}

int x = MyProperty; // Cannot be marked as "out" or "ref" because it is actually a method call

【讨论】:

    猜你喜欢
    • 2010-10-08
    • 2011-02-25
    • 2013-12-27
    • 2020-11-26
    • 1970-01-01
    • 2016-04-05
    • 2011-01-11
    • 2011-05-29
    相关资源
    最近更新 更多