2015-10-06 43 views
-4

我想輸出一個不斷變化的整數值在主要使用和多個其他類中創建。出於學習的目的,我看到是否有可能做我想做的事情,看看造成錯誤的原因。這裏的代碼:如何使用寫入行從另一個類打印整數值?

class Program 
{ 
    static void Main(string[] args) 
    { 
     // how do I avoid an identifier error with unit.() if the other class is unit:stats? 
     unit.(); 
     // how can I get the troop value from the unit:stats class? 
     Console.WriteLine(troop); 
    } 
} 
public class stats 
{ 
    public int troop; 
} 
public class unit : stats 
{ 
    public void archer() 
    { 
     troop = 100; 
    } 

} 
+3

'如果是possible',是的,只要瞭解基本的C# – Eser

回答

3

你需要有一個「實例」的對象。所以,在你主:

unit myUnit = new unit(); //Create an instance of unit 
myUnit.archer(); //Run the method that sets the troop number 
Console.WriteLine(myUnit.troop);//Access the troop value from myUnit 
+1

護理文檔進行評論downvoter? – MikeH

+0

@EZI它看起來像OP想要輸出一個值,而不是返回一個值。 – MikeH

+1

好的,不可編譯的答案,一個不可編譯的問題......(你怎麼認爲'部隊= 100;'應該工作。) – EZI