繁体   English   中英

如何通过 setter 设置属性

[英]How to set property via setter

我在学校学习过 C#。 我们做了一些基本的东西,比如循环、if 等。

现在我们做更多关于 OOP 的事情。 老师给我们讲了一些关于自动实现的属性,我觉得这个功能很棒。 但我很好奇如何通过方法设置属性值。

当我们不知道自动实现的属性时。 我们总是做一个方法来设置或获取类的值。 但是当我使用 auto-implemented-property 时,我看不到任何获取或设置类实例值的方法。 那么当我只能通过构造函数设置值时,如何设置类的某些属性的值。 我想知道,因为当属性是私有的时,我只能通过构造函数设置它,这不是问题,但是当我想通过 Console.Readline(); 设置值时我可以做什么; ?

namespace _001_dedicnost
{    
    class Car
    {        
        int Size { get; set; }                              
    }
    class Program
    {
        static void Main(string[] args)
        {
            Car car1 = new Car(5);
            // but the following line wont work
            car1.Set(51);
        }
    }
}

您的 Car 类具有私有属性 Size,因此您无法从您的代码中访问它,只能从 CAR 类中访问它

如果你想为这个属性设置值,你必须将它声明为 PUBLIC:

 class Car
        {
            public int Size { get; set; }
        }

        static void Main(string[] args)
        {
            Car car1 = new Car();
            car1.Size = 1;
        }

当您将属性放在表达式的左侧时,将自动调用 set 方法,并将表达式的右侧作为值。

所以car1.Size = 51就像调用value 51 的 Size 属性的扩展设置器。

这个

public class Point {
    public int X { get; set; } = 0;
}

等效于以下声明:

public class Point {
    private int __x = 0;
    public int X { get { return __x; } set { __x = value; } }
}

这意味着您在 c 锐利编译器下有“几个‘方法’,它们使用‘=’符号调用”

Point p = new Point();
p.X = 10; //c# compiler would call something like p.__set_X(10)
int i = p.X; //c# compiler would call something like int i = p.__get_X();

阅读有关自动属性的更多信息https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#automatically-implemented-properties

顺便说一句,我不建议使用它 - 它破坏了代码的可读性和可重构性;(

如果类是一个简单的贫血模型(没有逻辑),将属性设置为public ,它将起作用。

如果你想控制不变量(业务规则),你需要一个public Size { get; private set; } public Size { get; private set; } public Size { get; private set; }使用public void SetSize(int size) { /* ... */ }其中包含您的业务规则。

以下是 C# 中通常使用的三个“模式”:

// Anemic domain model (simple entity)
public class Car
{
    public int Size { get; set;}
}

// Domain model with business rules
public class Car
{
    public int Size { get; private set; }

    public void SetSize (int size)
    {
        // check to make sure size is within constraints
        if (size < 0 || size > 100)
            throw new ArgumentException(nameof(size));

        Size = size;
    }
}

// Value object
public class Car
{
    public Car (int size) 
    {
        // check constraints of size
        Size = size;
    }
    public int Size { get; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM