接口不通过引用传递

Cat*_*lin 2 c# asp.net pointers reference

我需要在运行时更改接口的实现.此接口由许多类引用.

这是我的测试用例,它没有像我期望的那样工作.(更改接口的引用似乎并未在其使用的所有位置更新)

这是一个例子:

// interface to change at runtime
interface IDiet
{
    void Eat();
}

class CarnivoreDiet : IDiet
{
    public void Eat()
    {
        Debug.WriteLine("Eat chicken");
    }
}

class HerbivoreDiet : IDiet
{
    public void Eat()
    {
        Debug.WriteLine("Eat spinach");
    }
}

class Human : IDiet
{
    private readonly IDiet _diet;
    public Human(IDiet diet)
    {
        _diet = diet;
    }

    public void Eat()
    {
        _diet.Eat();
    }
}

void Main()
{
    IDiet diet = new CarnivoreDiet();
    Human human = new Human(diet);
    human.Eat();
    // outputs "Eat chicken"

    diet = new HerbivoreDiet();
    human.Eat();
    // still outputs "Eat chicken" even if i changed the reference of IDiet interface
}
Run Code Online (Sandbox Code Playgroud)

为什么IDiet接口不在Human实例内更新?

PS:IDiet接口在很多类中使用,因此添加一个类似的方法SetDiet(IDiet diet)将不是一个解决方案.

Kha*_* TO 7

当您通过此代码传递对象引用时:

Human human = new Human(diet);
Run Code Online (Sandbox Code Playgroud)

引用(对象的地址)被复制到其参数:

public Human(IDiet diet)
{
        _diet = diet;
}
Run Code Online (Sandbox Code Playgroud)

它们是3个不同的内存块,包含对象的相同引用:原始内容diet,参数variable(diet)和类属性(_diet).

所以当你执行你的代码时:

diet = new HerbivoreDiet();
Run Code Online (Sandbox Code Playgroud)

此内存块现在包含对新对象(HerbivoreDiet)的引用,但Human仍然引用旧对象.