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

时间:2020-05-18 20:35:39

标签: c# .net

假设我有两个类,并且都包含相同的字段

public interface IDeprt
    {
        object BindData();
    }

我有一个接口和两个继承自该接口的类

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

和两个提取器类

<T>

所以我的问题是,如何使用.done(function (data) { var html = "" console.log(data); console.log(data[0].events) const events = data.map((row)=>{ return { title: row.events.title, start: row.events.start, end: "2020-05-18 18:00:00" } }) let calendar = new FullCalendar.Calendar(calendarEl, { // On charge le composant "dayGrid" plugins: ['dayGrid', 'timeGrid', 'list'], //defaultView: 'listMonth', //local :'fr', //traduction, header: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,list' }, buttonText: { today: 'aujourd\'hui', month: 'Mois', week: 'Semaine', list: 'liste' }, events, nowIndicator: true }); 以通用方式实现此目标。 两个类都执行相同的操作,只是返回类型更改。如果我以上述方式进行操作,则会有很多重复的代码。

1 个答案:

答案 0 :(得分:3)

使您的ITem界面和BindData通用名称使它们使用相同的通用参数。

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

然后实现如下子类:

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


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

编辑:随着问题的发展。

为A和B类提供一个共享的基类。

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

class A : CommonItem {   
}

class B : CommonItem {   
}

然后使用一种方法接受make类,该方法接受具有newCommonItem约束的通用参数。

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

用法:

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