-2

我在 Format1 类中有 9 个字符串,我想将它们转换为 Format2 类中看到的不同类型,但是 3 个字符串仍将保留为字符串类型。我决定开始和他们一起玩,直到我得到一个我满意的代码。

正如您在我的 Form1.cs 代码中看到的那样,在按钮单击事件时,我真正想做的就是调用 getConvert() 方法并让它处理所有事情。显然我错过了一些东西。我必须用我丑陋的 6 行来调用所有内容。

您可以在代码中的注释中看到我的非工作尝试。这次我做错了什么??

你也可以在这里获取我的资源: https ://mega.co.nz/#!64QzERRR!Qit9SDZQ7kW7rNAUUHHDRZUUvZY9z0ukgfuqVt00mE

public class Format1
    {
        public string Name { get; set; }
        public string Year { get; set; }
        public string Director { get; set; }
        public string AverageRating { get; set; }
        public string LeadingActor1 { get; set; }
        public string LeadingActor2 { get; set; }
        public string LeadingActor3 { get; set; }
        public string Language { get; set; }
        public string ImdbLink { get; set; }


    }



public class Format2 : Format1
    {
        public int Year { get; set; }
        public int AverageRating {get; set;}
        public string LeadingActors { get; set; }
        public bool IsInEnglish { get; set; }
        public bool HasImdbLink { get; set; }


        public Format2 getConvert()
        {

            Format2 converted = new Format2();




        //converted.Name = textBox1.Text;
        //textBox18.Text = converted.Name;

            converted.Name = this.Name;
            converted.Director = this.Director;
            converted.ImdbLink = this.ImdbLink;

            return converted;
        }
    }





namespace as3_DVDproject
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        Format2 converted = new Format2();

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void label9_Click(object sender, EventArgs e)
        {

        }

        private void okButton_Click(object sender, EventArgs e)
        {
            //converted.getConvert();

            converted.Name = textBox1.Text;
            textBox18.Text = converted.Name;

            converted.Director = textBox3.Text;
            textBox16.Text = converted.Director;

            converted.ImdbLink = textBox9.Text;
            textBox10.Text = converted.ImdbLink;

        }
    }
}
4

2 回答 2

1

更面向对象的模式是向采用 Format1 的 Format2 添加一个构造函数,或者为 Format2 提供一个采用 Format1 并返回 Format2 的静态方法。实际的映射代码在我看来并不那么冗长,您可以将它放在其中任何一个地方。

private void okButton_Click(object sender, EventArgs e)
{
    Format1 one = new Format1(textBox1.Text, converted.Name, textBox3.Text, converted.Director);
    Format2 two = new Format2(one);
}

您希望对象知道如何构建自己而不是在表单中构建它们。

于 2013-01-23T17:30:24.047 回答
1

至于您重新尝试(我认为问题在于)将 convert.Name 的值分配给 TextBox1 或使用 TextBox18 的反之亦然将失败,因为 TextBox 未在该类中声明,它们是在 Form1 类中声明的Format2 类无法访问。

于 2013-01-23T17:39:52.283 回答