gpt4 book ai didi

c# - 从父类参数获取子类类型

转载 作者:太空狗 更新时间:2023-10-30 00:58:16 28 4
gpt4 key购买 nike

我将拥有一个对象的多个“类型”,我真的不确定如何在不为每种类型单独保存/检索的情况下最好地检索/保存这些多个类型。

我的类(class):

public class Evaluation {
public int Id
public string Comment
}

public class EvaluationType_1 : Evaluation {
public string field
}

public class EvaluationType_1 : Evaluation {
public string field
}

我想在我的仓库中做什么:

public interface IEvaluationRepository {
public Evaluation getEvaluation(int id);
public SaveEvaluation(Evaluation);
}

在获取/保存方法中:

// Save/get common fields
Id
Comments

// Get child type, perform switch
Type childType = ???
switch(childType) {
// Set child-specific fields
}

我不想添加“类型”列,因为我在数据库的另一部分中有这个列,而且我不太喜欢它

更新

如有必要,这里有更多信息以供澄清。

我喜欢使用接口(interface)和泛型的想法,但我真的不知道如何将它们合并到我的存储库模式中。

当我调用 getEvaluation 时,我希望它返回一个抽象的 Evaluation,但我正在努力处理这段代码。与保存相同。

更新2

Daniel 正在帮助我深入了解我到底想问什么。

数据库:

Evaluations
Id (PK)
Comment

EvaluationType1
Id (FK to Evaluations.Id)
Field

EvaluationType1
Id (FK to Evaluations.Id)
Field

因此,在 getEvaluation(int id) 中,我需要弄清楚他们想要什么类型的评估。这是否意味着我应该传入一个类型? saveEvaluation 也是如此,但我可以做一个开关/函数映射来查看它是什么 Type

最佳答案

试试这个

public interface ISaveable {
void SaveFields();
}

public abstract class Evaluation : ISaveable {
public int Id
public string Comment

public virtual void SaveFields() {
//Save ID and Comments
}
}

public class EvaluationType_1 : Evaluation {
public string field1

public override void SaveFields() {
//Save field1
base.SaveFields();
}

}

public class EvaluationType_2 : Evaluation {
public string field2

public override void SaveFields() {
//Save field2
base.SaveFields();
}

}

然后你可以有一个 ISaveable 的集合,比如 List<ISaveable>并对每个调用 SaveFields,不管是什么类型。您现在是针对接口(interface)而不是针对具体类型进行编程。代码解耦的第一步。

已编辑:回应您的评论在您的存储库中,您将不再针对 Evaluation 类进行编程。相反,您将针对它实现的接口(interface)中的方法进行编程:

代替:

public interface IEvaluationRepository {
public Evaluation getEvaluation(int id);
public SaveEvaluation(Evaluation);
}

你可能有:

 public interface ISaveableRepository {
public ISaveable getSavable(int id);
public Save(ISaveable saveable);
}

存储库的实现可能是这样的:

 public class SaveableEvaluationRepository : ISaveableRepository {
public ISaveable getSavable(int id) {
//Add your logic here to retrieve your evaluations, although I think that
//this logic would belong elsewhere, rather than the saveable interface.
}

public Save(ISaveable saveable) {
saveable.SaveFields();
}
}

关于c# - 从父类参数获取子类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3188247/

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