在.Net中实现多个接口和对象实例

kev*_*aub 0 .net c# memory-management

以下是我正在做的一个简单示例.基本上,我有多个接口可以由1个类或单独的类实现,因此我将每个接口存储在应用程序中.我唯一的问题是变量myInterface,yourInterface和ourInterface. 他们引用相同的对象还是有3个不同的对象?

interface IMyInterface
{
    void MyFunction();
}

interface IYourInterface()
{
    void YourFunction();
}

interface IOurInterface()
{
    void OurFunction();
}

public class MainImplementation : IMyInterface, IYourInterface, IOurInterface
{
    public void MyFunction() { }
    public void YourFunction() { }
    public void OurFunction() { }
}

private IMyInterface myInterface;
private IYourInterface yourInterface;
private IOurInterface ourInterface;

static void Main(string[] args)
{
    myInterface = new MainImplementation() as IMyInterface;
    yourInterface = myInterface as IYourInterface;
    ourInterface = myInterface as IOurInterface;
}
Run Code Online (Sandbox Code Playgroud)

额外奖励:有更好的方法吗?

Noo*_*ilk 5

它们都引用相同的对象.因此,以下列形式对它们进行更改:

 ourInterface.X = ...
Run Code Online (Sandbox Code Playgroud)

将反映在"所有观点"中.

有效地你正在使用你的演员(我认为你的意思是你的最后一个'作为IOurInterface')给出了不同的数据"视图".在这种情况下,每个接口分别打开一个功能.