C# 泛型类还是泛型方法?哪一个是好的做法?

C# 泛型类还是泛型方法?哪一个是好的做法?,c#,.net,generics,C#,.net,Generics,我有3个不同的班级: class A { public int property1; public int property2; // so on.. } class B { public int property11; public int property22; //so on. } class Consumer { public int property111; public int property222; //so on. } // Busin

我有3个不同的班级:

class A
{
  public int property1;
  public int property2;
  // so on..
}

class B
{
  public int property11;
  public int property22;
  //so on.
}

class Consumer
{
  public int property111;
  public int property222;
  //so on.
}

// Business logic in other class
if (someCondition)
{
    var serviceCall1 = GetValuesForClassA();
    A obj = serviceCall.Response;
}

else if (someOtherCondition)
{
    var serviceCall2 = GetValuesForClassB();
    B obj = serviceCall2.Response;
}

在获得特定类型的值后,我通过一个通用函数将其分配给Consumer type的属性,如下所示:

private void ApplyProperties<T>(T serviceResponse, Consumer obj)
 where T: class
{
    if (serviceResponse.GetType().Name == "A") // where A = class name
    {
        A newObj = (A)(object)serviceResponse;

        //Assign properties of Consumer obj here.
    }
    else if(serviceResponse.GetType().Name == "B") // where B = class name
    {
        B newObj = (B)(object)serviceResponse;

        //Assign properties of Consumer obj here.
    }
}
private void applyproperty(T servicesponse,Consumer obj)
T:在哪里上课
{
if(serviceResponse.GetType().Name==“A”)//其中A=类名
{
newObj=(A)(对象)服务响应;
//在此处指定使用者对象的属性。
}
else if(serviceResponse.GetType().Name==“B”)//其中B=类名
{
B newObj=(B)(对象)服务响应;
//在此处指定使用者对象的属性。
}
}

我已经效仿了。我不清楚如何以更干净的方式更改代码,因此提出了这个问题。

您可以使用模式匹配

        if (serviceResponse is A newObj) // where A = class name
        {
            //Assign properties of Consumer obj here.
        }

如果代码根据其类型参数的类型输入不同的代码路径,可以说它不是泛型的。在这个意义上,“通用”意味着“适用于多种事物”。而您的代码没有,因为它一次只应用于一种类型。你可能不需要这里的泛型,也不需要所有的施法魔法。使用AutoMapper可能会更好,尤其是当可读代码是您的最终目标时。在泛型方法中进行类型检查意味着您的设计中存在错误。在这种情况下,使用重载方法或映射库是有意义的。您是否考虑过将
applyproperty
逻辑移动到类A和类B中?是的,但我不能这样做,因为这样做我必须在两个不同的位置编写类似类型的代码。现在ApplyProperty方法是CommonHelper类@MJwills中的通用方法,为什么不将类似的代码放在第三个类中,a和B可以在需要时调用?