gpt4 book ai didi

C#:关于接口(interface)、实现和继承的混淆

转载 作者:行者123 更新时间:2023-11-30 22:30:04 26 4
gpt4 key购买 nike

我想知道要走什么路,如果我需要发布数据接口(interface)但想在内部使用它们和扩展的计算属性。为了更清楚:

// 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;
}
}

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

最佳答案

您可以通过将 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);

关于C#:关于接口(interface)、实现和继承的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9885675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com