Get,Set,不返回大于运算符的内容

问题描述 投票:-1回答:1

我只是在测试某些东西,似乎无法按预期工作。我不明白为什么这行不通。

现在看,添加了应该正常工作的整个程序?:

    class Program
{
    static void Main(string[] args)
    {
        AgeGroup a = new AgeGroup();

        Console.Write("Write your age: ");
        a.AgeTest1 = Convert.ToInt32(Console.ReadLine());

        Console.ReadKey();

    }
}

public class AgeGroup
{
    private int age;

    public int AgeTest1
    {
        get { return this.age; }
        set
        {
            if (this.age > 65) 
                Console.WriteLine("Nope not working!");
            this.age = value;
        }


    }
}

}

c#
1个回答
2
投票

您正在测试背景字段的当前值,而不是分配给属性的值。我认为您的意思是:

public int AgeTest1
{
    get { return this.age; }
    set
    {
        if (value > 65)
            Console.WriteLine("Nope not working!");
        this.age = value;
    }
}

public int AgeTest1
{
    get { return this.age; }
    set
    {
        this.age = value;
        if (this.age > 65)
            Console.WriteLine("Nope not working!");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.