2013-01-23 22 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

很好的解釋!謝謝 –