首页 > 解决方案 > 采用任何属性类/模型 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);
   }
}

我希望接口方法被任何实现类调用并使用任何模型

标签: c#

解决方案


根据您的描述,您可能想要使用泛型。由于您正在创建单独的实现,您可以应用下面的接口来实现类似的结果。

public interface IModel<T>
{
   void Dosomething(T model);
}

public class ImplementationB : IModel<B>
{
   public void Dosomething(B model)
    {
      Console.WriteLine(model.someID);
    }
}

推荐阅读