显式列表错误输入类型?

时间:2010-12-07 11:43:24

标签: c# casting explicit

我正在尝试从存储过程的结果转换为List ..我已经为 timerangeResult - >的单个对象创建了显式(工作)强制转换。预订 ,但我错过了一个清单..

以下是代码:

public static explicit operator List<Booking>(timerangeResult t)
{
List<Booking> bL = new List<Booking>();
IEnumerable<timerangeResult> tx = (IEnumerable<timerangeResult>) t;

foreach (timerangeResult tt in tx)
{
 Booking b = (Booking)tt;
        bL.Add(b);
}
//return bL;
//return new List<Booking>(bL);
//return new List<Booking>(IEnumerable < Booking > bL);
return bL;
// [NONE OF THESE WORK]
// ERROR:
// User-defined conversion must convert to or from the enclosing type (UNDERLINED: "explicit operator List<Booking>" line 1)
}

提前致谢!

3 个答案:

答案 0 :(得分:3)

需要在所涉及的两种类型之一中定义强制转换运算符。在源操作数类型中,或在目标操作数类型中。

换句话说,您需要在以下位置定义运算符:

  • List<Booking>(这是不可能的)
  • ...或timerangeResult

我的猜测是你已经在其他地方定义了运算符,尝试将其移到timerangeResult类型。

另外,请注意显式运算符很难发现,你真的需要知道它们在那里。添加一个执行相同操作的实例方法通常要好得多,即:

public class timerangeResult
{
    ...

    public List<Booking> ToBookingList()
    {
        ...
    }
}

答案 1 :(得分:0)

运营商定义的是什么类型?该运算符只能在timerangeResult类中定义(因为List<Booking>,另一个选项,不在您的控制范围内)

答案 2 :(得分:0)

这就是我现在所拥有的(db.designer.cs)

public partial class timerangeResult
{

    private int _ID;

    private string _Login;

    private System.DateTime _Starts;

    private System.DateTime _Ends;

    private string _Delete;

    private byte _Notify;

// CUSTOM
//public static explicit operator List<Booking>(timerangeResult t)
public static List<Booking> ToBookingList(IEnumerable<timerangeResult> t)
{
    List<Booking> bL = new List<Booking>();

    foreach (timerangeResult tt in t)
    {
        Booking b = (Booking)tt;
        bL.Add(b);
    }
    return bL;
}
// CUSTOM END^

和.. Booking.cs

public static List<Booking> Today(DateTime begin, DateTime end)
{
    try
    {
        dbDataContext db = new dbDataContext();

        IEnumerable<timerangeResult> bQ = from b in db.timerange(begin, end)
                             select b;
        List<Booking> bL = timerangeResult.ToBookingList(bQ);

        return bL;
    }
    catch (Exception)
    {
        throw;
    }
}

现在我得到:“查询结果不能多​​次枚举。”

相关问题