c# - 不断变化的(虚构的)金钱

标签 c#

在使用古老的铜、银、金和白金货币系统的游戏中,每种面额的 100 个单位等于下一个最高面额的 1 个单位,这是可接受的“排序”或“在输入时向上改变'值?


public struct Coinage
{
    private int _copper;
    private int _silver;
    private int _gold;
    private int _platinum;

    public int Copper
    {
        get { return _copper; }
        set
        {
            int val = value;
            while (val > 99) { val -= 100; Silver ++; }
            _copper += val;
        }
    }
    public int Silver 
    { 
        get { return _silver; } 
        set 
        {
            int val = value;
            while (val > 99) { val -= 100; Gold ++; }
            _silver += val;
        } 
    }
    public int Gold
    {
        get { return _gold; }
        set
        {
            int val = value;
            while (val > 99) { val -= 100; Platinum ++; }
            _gold += val;
        }
    }
    public int Platinum { get { return _platinum; } set { _platinum = value; } }
}

那么无论我输入多少面额(低于白金),它都会正确地为我兑换货币?像这样链接属性的设置方法是个坏主意吗?有没有一种更有效的方法可以在单一方法中做到这一点?

谢谢。

最佳答案

好的 - 所以我评论说我会将其存储为一个值并根据需要显示。下面是一个快速而肮脏的实现来传达这个想法。我没有费心检查底片或优化 - 只是想传达这个想法。

public class Coinage
    {
        public long Copper { get; set; }

        public override string ToString()
        {
            long change = Copper;

            var denominations = new[] {"Gold", "Silver"};

            int numberOfDenominations = denominations.Count();

            var result = new StringBuilder();

            foreach (var denomination in denominations)
            {
                int coppersToCurrentDenomination = ((int) Math.Pow(100, numberOfDenominations));

                long currentAmount = change / coppersToCurrentDenomination;
                result.AppendFormat("{0}:{1}", denomination, currentAmount);
                change -= (currentAmount * coppersToCurrentDenomination);

                numberOfDenominations--;
            }

            result.AppendFormat("Copper:{0}", change);

            return result.ToString();
        }
    }

关于c# - 不断变化的(虚构的)金钱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3285917/

相关文章:

c# - 如何为未绑定(bind)列单元格设置值? (SetRowCellValue)Grinview Winforms Devexpress

c# - 比较两个复杂对象的最佳方法

c# - 在 WPF 中使用 ObservableCollection<Dictionary<String, Object>> 作为 DataGrid Itemsource

c# - 将巨大的 40000 页 pdf 拆分为单页,itextsharp,outofmemoryexception

c# - 为什么 list.count 在此代码中返回 0

c# - Silverlight 中的 TemplateBinding 和附加字符串

c# - 从 javascript 调用的 Web 服务中检索值?

c# - 如何将 C# 代码值访问到 javascript 中?

c# - 如何以编程方式更改窗体上的背景图像#

c# - 事件设计指南