2009-04-25 101 views
1

考虑这个类:C#控制台问题

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Game.Items 
{ 
    class Item 
    { 
     private string name; 
     public string Name 
     { 
      get { return this.name; } 
     } 

     private string description; 
     public string Description 
     { 
      get { return this.description; } 
     } 

     public Item(string name, string description) 
     { 
      this.name = name; 
      this.description = description; 
     } 

     public override string ToString() 
     { 
      return this.name; 
     } 
    } 
} 

我然后创建一个新的对象是这样的:

Item item1 = new Item("Item1", "Description..."); 

现在的问题,我不能与getter方法,即访问该对象的属性这是行不通的:

Console.WriteLine(item1.Name); 
Console.WriteLine(item1.Description); 
Console.ReadLine(); 

“不工作”我的意思是当我点击“开始调试”,控制台窗口出现,但没有g在那里,它是空白的。但是,这工作正常:

Console.WriteLine(item1); // ToString() 
Console.ReadLine(); 

我做错了什么?

理查德

+0

如果你还没有,请尝试安装ReSharper的的30天免费试用 - 它会检测并提供解决众多之类的命名空间的问题,保护问题和诸如此类的东西......以及建议良好的命名习惯 - 良好的学习材料。 – 2009-04-25 13:14:20

+0

当你说“这不起作用”时,你究竟是什么意思?编译器错误?运行时错误?不正确的结果?崩溃? – 2009-04-25 13:15:14

+0

换行符是打印还是什么都没有? “Console.ReadLine”怎么样?它工作吗? – 2009-04-25 13:44:37

回答

3

正常工作对我来说:

using System; 

namespace Application 
{ 
    class Test 
    { 
     static void Main() 
     { 
      Item item1 = new Item("Item1", "Description..."); 
      Console.WriteLine(item1.Name); 
      Console.WriteLine(item1.Description); 
     } 
    } 
} 

(随着你的类有作为)

当你说“这行不通”究竟是什么出了问题?

0

您是否在一个与“项目”包含的项目不同的项目中工作您的主类?如果是这样,那么

  • 参考其他项目
  • 标记您的项目类公共

    public class Item { 
        // your code 
    } 
    

或者你可以尝试访问此方法,如果这个问题与有关名称空间

Console.WriteLine(Application.item1.Name); 
Console.WriteLine(Application.item1.Description); 

另外,在e xecution,否则你的控制台窗口会不显示你什么

Console.ReadLine(); 

检查也使用条款中,根据最后的评论,你就必须在您正试图将文件的顶部使用using子句使用Item类

using Game;