c# - 采用任何属性类/模型 C# 的接口方法
问题描述
所以,我想创建一个接口,它有一个可以接受任何模型类的方法。例如
我有这三个属性类
class A
{
public long id { get; set; }
public string description { get; set; }
public string code { get; set; }
}
class B
{
public long someID { get; set; }
}
class C
{
public long anydesign { get; set; }
}
class D
{
public long Router { get; set; }
}
我有一个界面
public interface IModel
{
void Dosomething(A model); // Now in this example it takes the A model,But I want it to be set, so that that class that implements the interface can put any model as required
}
现在,我有一个实现模式的类由于接口只接受A模型,我可以在实现时在类中传入A模型
public class ImplemenationA: IModel
{
public void Dosomething(A model)
{
Console.WriteLine(model.description);
}
}
假设我有另一个实现类现在,我猜下面的一个不会工作,因为接口签名只强制采用模型 A 而不是任何其他模型
public class ImplementationB:IModel
{
public void Dosomething(B model)
{
Console.WriteLine(model.someID);
}
}
我希望接口方法被任何实现类调用并使用任何模型
解决方案
根据您的描述,您可能想要使用泛型。由于您正在创建单独的实现,您可以应用下面的接口来实现类似的结果。
public interface IModel<T>
{
void Dosomething(T model);
}
public class ImplementationB : IModel<B>
{
public void Dosomething(B model)
{
Console.WriteLine(model.someID);
}
}
推荐阅读
- flutter - 如何同时同步两个 CircularProgressIndicators?
- python - 使用本地文件作为 set_thumbnail 嵌入 Discord.py
- javascript - javascript元素出现然后消失
- node.js - Express.js StaticPath 问题 | CSS 未应用到一个页面,而 HBS 未加载到其他页面
- node.js - MongoDB在数组中查找对象
- python - 如何解决 400 statusCode 和 Unexpected character (at character 1) 错误?
- java - 使用 Jackson 将 POJO 序列化为 CBOR 时的整数键
- javascript - 有没有办法在调用一次函数时“重置”一个函数?
- python - 验证登录 Django 的自定义用户模型
- github - Github repo无法连接winscp、putty?