2011-06-11 36 views
-1

你好,我需要你的幫助訪問對象的參數..通過從另一個類(C#)的方法

我有一個2 CLASSE怎麼叫書和標題和一本名爲(字符串構造函數,字符串B,串c ,串d),並在主程序類我稱之爲列入標題等級看到下面的主類代碼方法AddCopy():

Book book1 = new Book("A", "B", "C","D"); 
book1.AddCopy(Copy copy); 

現在我的主要問題是:我如何可以訪問A, B,C,D參數在AddCopy方法中?

回答

2

構造函數調用的參數A,B,C和D都在構造函數中作用域 - 這意味着它們只在構造函數中可用。

要從AddCopy方法訪問它們的值,您需要將它們複製到構造函數中的類級別字段。

所以,你的書類成爲類似:

public class Book 
{ 
    private string _a; 
    private string _b; 
    private string _c; 
    private string _d; 

    public Book(string A, string B, string C, string D) 
    { 
     _a = A; 
     _b = B; 
     _c = C; 
     _d = D; 
    } 

    public void AddCopy(Copy copy) 
    { 
     // within this method you can access the private fields, but there is no 
     // way to access the A, B, C and D parameters of the constructor. 

     string someString = _a + _b + copy.SomeProperty; 
    } 
} 
+0

我怎樣才能將它們複製,我的意思是語法.. ??? – 2011-06-11 14:41:24

+0

只是添加到代碼來做到這一點。請注意,您不是自己訪問參數,您不會影響班級以外的值,只會影響班級副本。 (你可以影響外面的值,但這通常是一個壞主意 - 或者至少應該仔細考慮的事情) – 2011-06-11 14:43:28

+0

AddCopy屬性不在Book類中,但是在Title Class ... – 2011-06-11 14:48:29