c# - 这是将数据传递给方法的更好方法

标签 c# .net oop parameter-passing

假设我们有 2 个类 Expense1Expense2。哪个类实现优于另一个,或者哪个被认为更接近面向对象?

我一直认为 Exp2.Calculate(1.5M,2)exp1.Calculate() 并使用 exp1 类的属性作为计算方法所需的值。

费用1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class Expense1
{
    public decimal ExpenseValue { get; set; }
    public int NumberOfItems { get; set; }
    private decimal result;

    public decimal Result
    {
        get
        {
            return this.NumberOfItems * this.ExpenseValue;
        }
    }

    public void Calculate()
    {
        this.result = this.ExpenseValue * this.NumberOfItems;
    }

    public void expense1()
    {
        this.ExpenseValue = 0;
        this.NumberOfItems = 0;
    }
}

费用2

class Expense2
{
    public decimal Calculate(decimal expenseValue, int numberOfItems)
    {
        return expenseValue * numberOfItems;
    }
}

两个类的实现

class Program
{
    static void Main(string[] args)
    {

        Expense1 exp1 = new Expense1();
        exp1.NumberOfItems = 2;
        exp1.ExpenseValue = 1.5M ;
        exp1.Calculate();
        Console.WriteLine("Expense1:" + exp1.Result.ToString());

        Expense2 exp2 = new Expense2();
        string result = string.Empty;
        result = exp2.Calculate(1.5M,2).ToString();
        Console.WriteLine("Expense2:" + result);
        Console.ReadKey();
    }
}

最佳答案

Expense2 更容易阅读和理解发生了什么,因为从调用中可以明显看出使用了哪些参数。

Expense1 可能会产生各种副作用,因为调用者可能会在调用 Calculate() 之前忘记设置用于计算的变量。

如果您需要访问用于稍后计算结果的值,您可以使用类似这样的东西

public class Expense {
    public decimal ExpenseValue { get; private set; }
    public int NumberOfItems { get; private set; }
    public decimal Result { get; private set; }


    public decimal Calculate(decimal expenseValue, int numberOfItems) {
        ExpenseValue = expenseValue;
        NumberOfItems = numberOfItems;
        Result = ExpenseValue * NumberOfItems;

        return Result;
    }

    public Expense() {
        Calculate(0, 0);
    }
}

这将允许 Expense 的内部状态在对象的生命周期内保持一致,并定义其Calculated

关于c# - 这是将数据传递给方法的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31695417/

相关文章:

c# - 桌面应用程序的应用程序内购买

.net - .net 中是否有用于注册表项路径的 Path.Combine?

php - 在匿名函数中使用 static::method() 会在 PHP 版本之间产生不同的结果

c# - 我可以将 C# 输出通过管道传输到 PHP 吗?

c# - 传入 XML 的验证 - 我是否应该同时使用 XSD 文件和代码验证

c# using 语句 with double IDisposable

.net - 如何在 Activator.CreateInstance 中传递 ctor args 或使用 IL?

关于 count_if : expected primary-expression before 的 C++ 错误

c++ - 如何在不导出对象的情况下自动删除对象

c# - 垃圾回收如何处理对象引用?