小编Laz*_*tle的帖子

我需要更改什么才能正确实施SOLID设计?

我正在尝试学习SOLID设计,并认为自己犯了一个错误。我认为该IItem接口在我的课程中不遵循Liskov替换原则Player但是,我无法解决该问题。如果我从IItem添加新的界面图,则必须更改Player的方法以添加用于处理它的外壳。

我希望Player类仅需要一种装备方法,因此需要帮助来了解我做错了什么以及如何正确做。

我的界面的简化版本:

    interface IItem
    {
        string Name { get; set; }
        int Value { get; set; }
        Quality Quality { get; set; }
        EquipmentType Type { get; set; }
    }
    interface IWeapon : IItem
    {

    }
    interface IArmour : IItem
    {
        int Defence { get; set; }
        Slot Slot { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

消费类Player:

    class Player
    {
        private Dictionary<Slot, IArmour> armour = new Dictionary<Slot, IArmour>();
        private IWeapon weapon;

        public bool Equip(IItem item) …
Run Code Online (Sandbox Code Playgroud)

c# .net-4.5

3
推荐指数
1
解决办法
44
查看次数

何时在方法中返回“this”而不是“void”,为什么?

在修改自身的方法中返回对“this”对象的引用有什么好处(或缺点)?什么时候应该使用返回“this”而不是 void?

当查看代码审查堆栈交换的答案时,我注意到答案在自操作方法中使用了“返回此”。

原始类的简化:

class Item
{
    public Item(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }

    public Item AddComponent(ItemComponent component)
    {
        _components.Add(component);
        return this;
    }

    private List<ItemComponent> _components = new List<ItemComponent>();
}
Run Code Online (Sandbox Code Playgroud)

使用代码简化:

var fireSword = new Item("Lightbringer")
                   .AddComponent(new Valuable { Cost = 1000 })
                   .AddComponent(new PhysicalDamage { Slashing = 10 });
Run Code Online (Sandbox Code Playgroud)

相关问题似乎不同用户的答案相互矛盾。

这个问题也与引用在对象创建中使用的流畅接口的答案类似。

c# oop fluent-interface method-chaining

2
推荐指数
1
解决办法
1247
查看次数

标签 统计

c# ×2

.net-4.5 ×1

fluent-interface ×1

method-chaining ×1

oop ×1