用于扩展方法的自定义通用列表

时间:2017-03-06 19:22:44

标签: c# generics

我有以下课程:

public class ListDemo<T> : IList<T>
{
    private List<T> list = new List<T>(); // Internal list
    public void Add(T item)
    {
       // Do your pre-add logic here
       list.Add(item); // add to the internal list
       // Do your post-add logic here
    }

    // Implement all IList<T> methods, just passing through to list, such as:
}

然后在我的代码中我有:

AuditList<Entities.SetupCenterCode> _centerCodes = new AuditList<Entities.SetupCenterCode>();

using (Logistics.Data.ConfigurationWCF svc = new Data.ConfigurationWCF())
{
    _centerCodes = svc.GetCenterCodes(_entity);

    foreach (var item in _centerCodes)
    {
        item.StartTracking();
    }
}

但我在转化时收到错误,因为svc.GetCenterCodes(_entity);会返回传统的List<>

enter image description here

我如何解决这个问题,这很奇怪,因为我的自定义ListDemo类是为通用列表构建的。

  

有任何线索吗?

1 个答案:

答案 0 :(得分:0)

你可以有一个私有构造函数,它接受一个列表,然后使用隐式运算符直接从列表中转换:

  CREATE EXTERNAL TABLE sorted (
    key string,
    value string
  )
  ROW FORMAT DELIMITED
  FIELDS TERMINATED BY '\t'
  STORED AS TEXTFILE
  LOCATION 's3://bucket/output/';

  SET hive.exec.reducers.max=1;
  SET mapred.reduce.tasks=1;

  INSERT OVERWRITE TABLE sorted
    SELECT * FROM input_data
    ORDER BY input_data.key;

然后,您的其余代码将无需更改即可运行:

public class MyList<T>
{
    private List<T> myList;

    private MyList(List<T> myList)
    {
        this.myList = myList;
    }

    public static implicit operator MyList<T>(List<T> list)
    {
        return new MyList<T>(list);
    }
}