所以,我想创建一个接口,它有一个可以接受任何模型类的方法.例如
我有这三个属性类
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; }
}
Run Code Online (Sandbox Code Playgroud)
我有一个界面
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
}
Run Code Online (Sandbox Code Playgroud)
现在,我有一个实现模式的类由于接口只接受A模型,我可以在实现过程中传入类中的A模型
public class ImplemenationA: IModel
{
public void Dosomething(A model)
{
Console.WriteLine(model.description);
}
}
Run Code Online (Sandbox Code Playgroud)
说我有另一个实现类现在,我猜测下面的一个不会工作,因为接口签名强制只采取模型A而不是任何其他模型
public class ImplementationB:IModel
{
public void Dosomething(B model)
{
Console.WriteLine(model.someID);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望接口方法可以被任何实现类调用并使用任何模型
根据您的描述,您可能希望使用泛型.由于您正在创建单独的实现,因此可以应用下面的接口来实现类似的结果.
public interface IModel<T>
{
void Dosomething(T model);
}
Run Code Online (Sandbox Code Playgroud)
public class ImplementationB : IModel<B>
{
public void Dosomething(B model)
{
Console.WriteLine(model.someID);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |