简体   繁体   中英

How to use an interface privately

I am attempting to use an interface privately inside of a few different classes. However I wont let me call the function inside the getter you see below:

public abstract class PreFabComponent : IAccountable
{

    //This represents the cumulative cost of all members, connectors, and supporting hardware
    private double materialsCost;
    protected double MaterialsCost
    {
        get 
        { 
             materialsCost = CalculateSelfCost();
             return materialsCost;
        }
    }




    //  Returns the sum of all Cumulative costs
    double IAccountable.CalculateSelfCost()
    {
        double sum = 0;

        foreach (IAccountable item in accountableItemsContatined)
        {
           sum += item.CalculateSelfCost();
        }

        return sum;
    }
}

Here is the interface

interface IAccountable
{
    double CalculateSelfCost();
}

How can I fix this?

You need to do an explicit cast:

private double materialsCost;
protected double MaterialsCost
{
    get 
    { 
         materialsCost = (this as IAccountable).CalculateSelfCost();
         return materialsCost;
    }
}

Basically, explicit interface method implementations are separate from other methods of a class. You simply can't call them without an explicit cast to the containing interface. In fact, there is no virtual method CalculateSelfCost in your class, in a manner of speaking.

If you want to know more about this, here is a good start - http://msdn.microsoft.com/en-us/magazine/cc163791.aspx (look specifically for the MethodTable section). You can see that the method tables for the interfaces you're implementing are separate from the method table of your class proper. In the case of implicit interface method implementations, both the main method table and the interface method table contain the reference, while in explicit implementations, the main method table doesn't have the reference at all. Now, details like this don't usually matter at all to the end-programmer, but I hope this satisfied your curiosity :)

This also has a couple of practical reasons unrelated to the internals or encapsulation practices, for example, if you had two explicit implementations of a method with the same signature but on two different interfaces, which one would you be actually calling? Rather than trying to solve the ambiguity, you simply have to always call the method properly, with the explicit interface included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM