2013-01-23 100 views
-2

我有Format1类中的9个字符串,我想转换成Format2类中看到的不同类型,但是3个字符串仍将保留为字符串类型。我决定开始和他们一起玩,直到我得到一个我很满意的代码。c#访问对象和类使用方法

正如你在我的Form1.cs代码中看到的,我真正想要做的事情就是调用getConvert()方法并让它处理所有事情。突然间,我错过了一些东西。我必须用我丑陋的6行来调用所有的东西。

你在代码中看到我的非工作尝试。我这次做错了什么?

您还可以在这里抢我的源: https://mega.co.nz/#!64QzERRR!Qit9SDZQ7kW7rNCAUUHHDRZUUvZY9z0ukgfuqVt00mE

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; 

     } 
    } 
} 

回答

1

的更多的面向对象模式会以添加一个构造函数格式2,需要一个格式1,或给格式2,需要一个格式1的静态方法并返回一个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); 
} 

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

+0

谢谢!这是我正在寻找的。我会尽力尝试一下^ _^ –

1

只要你想出的尝试(我认为这个问题是关于)将转换。名称的值分配给TextBox1或反之亦然TextBox18将失败,因为TextBoxes没有在该类中声明,他们宣布在Form1类中,无法对类Format2访问。

+0

很好的解释!谢谢 –