具有硬编码 getter 和 setter 的 C# 属性

标签 c# .net

我有一个属性定义为...

public List<Obj> Objs { get; set; }

我希望能够做的是将一些逻辑放入 get 方法中,所以它看起来像...

public List<Obj> Objs
{
    get
    {
        if (Objs == null)
        {
            Objs = new List<Obj>();
        }
        if (Objs.Count < 1)
        {
            Objs.Add(new Obj());
        }
        return Objs;
    }
    set { Objs = value; }
} 

现在,当我这样做时,我收到一条错误消息,告诉我该函数在所有路径上都是递归的。

有没有办法在不创建私有(private)支持字段的情况下做到这一点?

最佳答案

必须创建一个私有(private)字段:

    private List<Obj> _objs;
    public List<Obj> Objs
    {
        get
        {
            if (_objs== null)
            {
                _objs= new List<Obj>();
            }
            if (_objs.Count < 1)
            {
                _objs.Add(new Obj());
            }
            return _objs;
        }
        set { _objs= value; }
    } 

为什么不可能?让我们用 Java 做同样的事情:

    private List<Obj> objs;
    public List<Obj> getListObjs()
    {
        ...
        // Recursion
        return getListObjs();
    }

关于具有硬编码 getter 和 setter 的 C# 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16885868/

相关文章:

c# - 在 C# 中将元素添加到列表的子列表

.net - 程序集存在于 GAC 中,但系统仅在复制到本地目录时才找到它。为什么?

c# - 为什么我可以使用 FileInfo 删除 .NET 中打开的图像文件?

c# - 检查对象是否为数字

java - 通过java或c#转换为exe的PDF安全性

c# - 当我调用 Bitmap.Save 函数时发生错误 "A generic error occurred in GDI+"

c# - ListView SelectedItem 的属性和 TextBox 绑定(bind)发生 ArgumentException

.net - Visual Studio 中的 F# 交互式热键

.net - Python 中 .Net InvalidOperationException 的类比是什么?

c# - Entity Framework 脚本生成