gpt4 book ai didi

c# - 使用泛型方法创建接口(interface)

转载 作者:行者123 更新时间:2023-11-30 16:59:49 27 4
gpt4 key购买 nike

我正在尝试设计一个接口(interface),使其具有通用类型 id 和一个通用方法,该方法返回实现该接口(interface)的类的类型。例如:

public interface IEntity <IDType, MethodReturnType>
{
IDType ID {get; set;}
MethodReturnType Get();
}

public class Model : IEntity<int, Model>
{
int ID {get; set; }
Model Get() { // do something }
}

我的问题是,将 Model 作为 IEntity 的第二个类型参数放入似乎很愚蠢,因为我已经在 Model 的类中,它应该是某种智能方式来弄清楚它是什么类型(尽管使用泛型类型需要它要在编译时间之前确定)。

是否有任何其他解决方案可以帮助我摆脱 Model 类型,同时保留接口(interface)中的 Get 方法定义?

最佳答案

在这种情况下,有两种典型的方法来设计您的类和接口(interface)。我会略微偏离您的确切示例,以尝试使答案更笼统。

选择哪个选项实际上取决于您希望如何使用您的类和接口(interface)。

选项 1

使您的接口(interface)通用,以便接口(interface)成员知道确切的类型。

public interface IEntity<TDescription>
{
TDescription Get();
}

public class MyModel : IEntity<MyDescription>
{
MyDescription Get() { ... }
}

public class MyDescription { ... }

这意味着当你使用你的界面时IEntity<TDescription>你需要知道TDescription在使用的时候。好处是您可以获得更多的编译时类型检查。

选项 2

不要让你的接口(interface)通用,而是让你的接口(interface)成员也使用接口(interface)。

public interface IEntity
{
IDescription Get();
}

public interface IDescription { ... }

public class MyModel : IEntity
{
MyDescription Get() { ... }
IDescription IEntity.Get() { return this.Get(); }
}

public class MyDescription : IDescription { ... }

这更灵活,但也意味着更少的编译时类型检查。

关于c# - 使用泛型方法创建接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23207277/

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