C# 采用任何属性类/模型C的接口方法#
所以,我想创建一个接口,它有一个可以接受任何模型类的方法。比如说 我有这三个属性类C# 采用任何属性类/模型C的接口方法#,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 anyde
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);
}
公共接口IModel
{
空洞剂量测定(T型);
}
公共类实现b:IModel
{
公共空间剂量测定(B型)
{
Console.WriteLine(model.someID);
}
}
某种装饰模式可以解决这个问题,将您的实际实现推迟到内部类并坚持关注点分离,如果我没有理解您的问题,请留下评论:
//added to support inner implementation
interface IModelImpl {
void Do();
}
class A: IModelImpl
{
public long id { get; set; }
public string description { get; set; }
public string code { get; set; }
public void Do(){
console.WriteLine(this.description);
}
}
class B: IModelImpl
{
public long someID { get; set; }
public void Do(){
console.WriteLine(this.someID);
}
}
class C: IModelImpl
{
public long anydesign { get; set; }
public void Do(){
...
}
}
这是您的IModel,基本相同,被视为外部实现:
public interface IModel
{
void Dosomething(IModelImpl model); //put any model as long it implements IModelImpl
}
您的类实现现在应更改为:
public class ImplemenationA: IModel
{
public void Dosomething(IModelImpl model)
{
//Do more specific work to ImplementationA
model.Do();
}
}
另一个类实现:
public class ImplementationB:IModel
{
public void Dosomething(IModelImpl model)
{
//Do more specific work to ImplementationB like validation
model.Do();
}
}
我很确定你正在寻找更具体的方法,如果接口有一个与模型无关的方法,比如公共接口IModel{void Dosomething(T model);void Donothing(string nothing);}是的,它会。您将在IModel接口中为void DoNothing(字符串nothing)包含一个方法定义。然而,这将要求您在实现IModel的所有类中实现该方法
public class ImplementationB:IModel
{
public void Dosomething(IModelImpl model)
{
//Do more specific work to ImplementationB like validation
model.Do();
}
}