简体   繁体   English

两种不同的类型,C#中的一种方法实现

[英]Two different types, one method implementation in C#

What would be best approach to implement this scenario: There is service method and two types, which differs only on List items type:实现此方案的最佳方法是:有服务方法和两种类型,仅在列表项类型上有所不同:

public long MyMethod(MyType request) {...}

Also i have two models, which are almost similar:我也有两个模型,它们几乎相似:

public class MyType {
    public int amount {get; set;}
    public List<MyDetailsType> details {get; set;}
}

public class MyType2 {
    public int amount {get; set;}
    public List<MyDetailsType2> details {get; set;}
}

How to make this one method如何制作这一种方法

public long MyMethod(MyType request) {...}

work for both request types without overload ?适用于两种请求类型而不会过载 Interface?界面? Abstract class?摘要 class? Virtual?虚拟的? Also the method is called once, so generic type not work, because method need parameter type defined, which i dont know until variable not set.该方法也被调用一次,因此泛型类型不起作用,因为方法需要定义参数类型,直到未设置变量我才知道。

App flow is as follows:应用流程如下:

  • Get request获取请求
  • Request is generated by some conditions to MyType or MyType2请求由某些条件生成到 MyType 或 MyType2
  • Call to MyMethod调用 MyMethod
Method1(SomeType request) {
    var request;
    if(a) {
       request = new MyType();
    } else {
       request = new MyType2();
    }

    MyMethod(request);
}

Here's a possible solution:这是一个可能的解决方案:

public long MyMethod<T>(MyBaseType<T> request) { ... }

public abstract class MyBaseType<T>
{
    public int Amount { get; set; }
    public List<T> Details { get; set; }
}

public class MyType : MyBaseType<MyDetailsType>
{
    // additional code
}

public class MyType2 : MyBaseType<MyDetailsType2>
{
    // additional code
}

If no additional code is needed for the derived classes, you can just use one class (without the abstract keyword).如果派生类不需要额外的代码,您可以只使用一个 class(不带abstract关键字)。

The Method1 code would look something like this: Method1代码如下所示:

void Method1(SomeType request)
{
    if (a)
       request = new MyBaseType<MyDetailsType>();
    else
       request = new MyBaseType<MyDetailsType2>();

    MyMethod(request);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM