C#:关于接口,实现和继承的困惑

时间:2012-03-27 08:16:31

标签: c# inheritance interface implementation

我想知道要走的路是什么,如果我需要公开数据接口但想要在内部使用扩展的计算属性。为了更清楚:

// The public interface
public interface IData
{
    int Property { get; }
}

// The internal interface
internal interface IExtendedData : IData
{
    int ExtendedProperty { get; }
}

// The assumed implementation of someone using my interface
public class Data : IData
{
    public Data(int a)
    {
        Property = a;
    }

    public int Property
    {
        get;
        private set;
    }

    public override string ToString()
    {
        return Property.ToString();
    }
}

// My implementation
internal class ExtendedData : IExtendedData
{
    public ExtendedData(int a)
    {
        Property = a;
    }

    public int Property
    {
        get;
        private set;
    }

    public int ExtendedProperty
    {
        get
        {
            return 2 * Property;
        }
    }

    public override string ToString()
    {
        return Property.ToString() + ExtendedProperty.ToString();
    }
}

// publicated by me, for the person who uses my dll
public static class Calculations
{
    public static int DoSomeCalculation(IData data, int parameter)
    {
        // This probably don't work, but maybe shows what I want to do
        IExtendedData tempData = (ExtendedData)data;
        return tempData.ExtendedProperty * parameter;
    }
}

我真的很沮丧,因为我觉得缺少一些基本的编程技巧。

2 个答案:

答案 0 :(得分:3)

您可以通过将ExtendedData实现为实现IData的类的包装器来解决此问题

internal class ExtendedData : IExtendedData
{

    private IData data;
    public ExtendedData(IData data)
    {
        this.data = data;
    }

    public int Property
    {
        get { return data.Property; }
        private set { data.Property = value; }
    }

    public int ExtendedProperty
    {
        get
        {
            return 2 * Property;
        }
    }    
}

并在DoSomeCalculation中使用

 IExtendedData tempData = new ExtendedData(data);

答案 1 :(得分:0)

ExtendedData可以从Data继承:

class ExtendedData : Data
{...}

为了创建Data对象,您可以像这样添加工厂:

public class DataFactory
{
    public IData CreateData()
    {
        return new ExtendedData();
    }
}

用户必须通过此工厂创建其所有 Data 对象。您可以通过将 Data 的构造函数设置为内部来确保它 在您的DLL中,您可以转换为ExtendedData