2011-06-11 35 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