将数据从一个类转换为另一个类

时间:2016-01-10 10:43:03

标签: c# wpf linq wcf combobox

我试图将数据从一个 ExtensionMethods 类转换为另一个名为 ComboBoxViewItem

的类

ExtensionMethods

public static class ExtensionMethods
{
    public static int GetDisplayItemId(this ComboBox combobox)
    {
        if (combobox.SelectedItem == null)
            return 0;
        else
            return ((DisplayItems)combobox.SelectedItem).Id; //Error here
    }
}

ComboBoxViewItem

class ComboBoxViewItem<T>
{
    private string name;
    public T Item { get; set; }

    public ComboBoxViewItem(T item, string name)
    {
        this.Item = item;
        this.name = name;
    }

    public ComboBoxViewItem(T item)
    {
        var prop = item.GetType().GetProperty("Name");
        if (prop == null)
            throw new ArgumentException("This object does not have a Name property, please use the other contructor.");
        if (prop.PropertyType != typeof(string))
            throw new ArgumentException("The property Name MUST be of type string. Please use the other contructor instead.");
        this.Item = item;
        this.name = (string)prop.GetValue(item);
    }

    public override string ToString()
    {
        return name;
    }
}

第1步现在我要做的就是将我的WCF服务中的数据加载到我的组合框中,如下所示:

public async Task LoadCompanies()
{
    using (MKCServiceClient service = new MKCServiceClient())
    {
        var companies = await service.GetCompaniesAsync();
        foreach (var company in companies)
            cmbQuoteCompany.Items.Add(new ComboBoxViewItem<Company>(company));
        cmbQuoteCompany.SelectedIndex = 0;
    }
} //Coding works fine and loads data into the combobox

第2步我想在组合框中添加要添加的数据,否则使用以下方法添加到另一个表中的位置:

private async void btnQuoteAdd_Click(object sender, RoutedEventArgs e)
{
    using (MKCServiceClient service = new MKCServiceClient())
    {
        quoteInformation = await service.GetQuoteAsync(new QuoteData
        {
            CompanyId = cmbQuoteCompany.GetDisplayItemId(), //I use ExtensionMethods class here
            BranchId = cmbQuoteBranch.GetDisplayItemId(), //Here
            CustomerId = cmbQuoteContact.GetDisplayItemId(), //Here
            CustomerRFQ = txtQuoteCustomerRFQ.Text,
            Date = dpQuoteDate.Text,
            Item = txtQuoteItem.Text,
            Material = txtQuoteMaterial.Text,
            Description = txtQuoteDescription.Text,
            Quantity = Convert.ToInt32(txtQuoteQTY.Text)
        });

        await service.FinalizeQuoteAsync(finalizeQuote);
    }
}

我的最终目标是在我的组合框中获取所选项目的 Id ,然后将其插入我的数据库。

在我调用 btnQuoteAdd_Click 方法后,我的应用程序崩溃并给我以下错误

  

无法转换类型的对象   &#39; MKCWorkflowApplication.ComboBoxViewItem`1 [MKCWorkflowApplication.WorkflowService.Company]&#39;   输入&#39; MKCWorkflowApplication.DisplayItems&#39;。

我在这里发布此问题的原因是因为我从一位知道C#比我更多的朋友那里得到了这个编码,我们不再联系了,所以我不# 39;知道如何解决这个问题:( 所以,如果有人能弄清楚发生了什么,请帮忙!谢谢。

1 个答案:

答案 0 :(得分:1)

您的扩展方法GetDisplayItemID期望填充了类DisplayItem的实例的组合框未填充ComboBoxViewItem的实例,因此内部转换失败。如果您的班级公司,报价和客户提供了一个缩进的命名属性ID,则可以编写可能的解决方法。

您可以用这种方式重写ComboBoxViewItem<T>课程

class ComboBoxViewItem<T>
{
    public string Name;
    public int ID;
    public T Item { get; set; }

    public ComboBoxViewItem(T item, string name, int id)
    {
        this.Item = item;
        this.Name = name;
        this.ID = id;
    }

    public ComboBoxViewItem(T item)
    {
        var prop = item.GetType().GetProperty("Name");
        if (prop == null)
            throw new ArgumentException("This object does not have ...");
        if (prop.PropertyType != typeof(string))
            throw new ArgumentException("The property Name MUST be of type...");
        this.Name = (string)prop.GetValue(item);
        prop = item.GetType().GetProperty("ID");
        if (prop == null)
            throw new ArgumentException("This object does not have ...");
        if (prop.PropertyType != typeof(int))
            throw new ArgumentException("The property ID MUST be of ...");
        this.ID = (int)prop.GetValue(item);
        this.Item = item;
    }
    public override string ToString()
    {
        // C# 6.0 string interpolation
        //return string.Format($"{ID}, ({Name})");

        // C# Standard string formatting
        return string.Format("{0}, ({1})", ID, Name);
    }
}

现在,您可以使用此语法从组合框中检索ID,而无需使用旧的扩展方法或定义新的扩展方法。

CustomerId = (cmbQuoteContact.SelectedItem as ComboBoxViewItem<Customer>).Item.ID
....