简体   繁体   English

泛型类型参数 C# - 如何泛型 class 返回类型

[英]Generic type parameters C# - How to generic class return type

Suppose I have two classes and both contain the same fields假设我有两个类并且都包含相同的字段

Class A  
{
    public string Name { get; set; }
    public int Designaton { get; set; }
}

Class B 
{
    public string Name { get; set; }
    public int Designation { get; set; }
}

And I have one interface and two classes which are inherited from interface我有一个接口和两个继承自接口的类

public interface IDeprt
{
    object BindData();
}

And two extractor classes:和两个提取器类:

public classAItem : IDeprt
{
    public object BindData()
    {
        return new A()
                   {
                       // mapping operation
                   }
    }
}

public classBItem : IDeprt
{
     public object BindData() 
     {
         return new B()
                    {
                         //same mapping operation
                    }
     }
 }
   

My question, how can I implement this in generic way using <T> .我的问题是,如何使用<T>以通用方式实现这一点。 Both classes are doing same operation only return type change.两个类都在执行相同的操作,仅返回类型更改。 If I am doing in the above way there is lot of duplication of code.如果我按照上述方式进行操作,则会有很多重复的代码。

Make your ITem interface and also BindData generic make them use the same generic parameter.使您的ITem接口和BindData通用使它们使用相同的通用参数。

public interface IItem<T>
{
   T BindData();
}

Then implement the subclasses like below:然后实现如下子类:

public class AItem : ITem<A>
{
  public A BindData(){
    return new A(){
     // mapping operation
    }
  }
}


public class BItem : ITem<B>
{
    public B BindData(){
       return new B(){
         //same mapping operation
        }
    }
}

Edit: As the question evolves.编辑:随着问题的发展。

Make a shared base class for A and B classes.为 A 类和 B 类创建一个共享基础 class。

public abstract class CommonItem 
{
   public string Name { get; set; }
   public  int Designaton { get; set; }
}

class A : CommonItem 
{   
}

class B : CommonItem 
{   
}

Then make class with a method that accepts a generic parameter with new and CommonItem constraints.然后使用接受具有newCommonItem约束的通用参数的方法制作 class。

public class Binder
{
    public T BindData<T>() where T: CommonItem, new()
    {
       return new T()
                  {
                       // you can access the properties defined in  ICommonItem
                  }
    }
}

Usage:用法:

var binder = new Binder();
var boundA = binder.BindData<A>();
var boundB = binder.BindData<B>();

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

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