gpt4 book ai didi

c# - 如果这也是一个接口(interface),则提取接口(interface)会隐藏成员的细节

转载 作者:太空狗 更新时间:2023-10-30 00:59:31 25 4
gpt4 key购买 nike

我有一个 Project 类,我想从中提取一个接口(interface),因为我们将处理不同类型的项目。 Project 的属性之一称为 Data:

class Project {
public Data D {get;}
public void SomeSpecificMethodReferencingData()
{
D.SomeSpecificMethod();
}
}

class Data {
public void SomeGenericMethod() { }
public void SomeSpecificMethod() { }
}

现在,Data 也需要作为接口(interface)提取(但只定义了 SomeGenericMethod()。我目前正在使用这个:

interface IProject {
IData D {get;}
}

interface IData {
void SomeGenericMethod();
}

class Data : IData {
public void SomeGenericMethod() { }
public void SomeSpecificMethod() { }
}

class OtherData : IData {
public void SomeGenericMethod() { }
public int SomeOtherSpecificMethod(float someArgument) { }
}

class Project : IProject {
public IData D { get; }
public void SomeSpecificMethodReferencingData()
{
D.SomeSpecificMethod(); // this does not work!
(D as Data).SomeSpecificMethod(); // this looks stupid!
}
}

class OtherProject : IProject {
public IData D { get; }
public void SomeOSpecificMethodReferencingOtherData()
{
var i = D.SomeOtherSpecificMethod(14.0f); // this does not work!
var i = (D as OtherData).SomeOtherSpecificMethod(14.0f); // this looks stupid!
}
}

我遇到的问题是,在 Project 类中,我引用了 SomeSpecificMethod。但是,当我为 Data 提取接口(interface)时,我首先必须将其从 IData 转换为能够引用特定方法。这是不可取的,因为 IData 始终是该项目的数据实例。当我构建我的 OtherProject 时,我将为它创建一个 OtherData,以便获得成对的 xxxProject 和 xxxData 实现。

是否有某种设计模式可以帮助我构建成对的相关类和引用类?类似于抽象工厂,但更好?

最佳答案

你可以为此使用泛型:

interface IProject<T> where T: IData {
T D {get;}
}

现在你的不同项目是这样的:

class Project : IProject<Data> 
{
public Data D { get; }
public void SomeSpecificMethodReferencingData()
{
D.SomeSpecificMethod(); // D is of type Data
}
}

class OtherProject : IProject<OtherData> {
public OtherData D { get; }
public void SomeOSpecificMethodReferencingOtherData()
{
D.SomeOtherSpecificMethod(14.0f); // D is of type OtherData
}
}

关于c# - 如果这也是一个接口(interface),则提取接口(interface)会隐藏成员的细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58131146/

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