2014-02-07 436 views
0

所以,我有一个班学生,并且我创建了一个指向类student的对象的引用变量。我想要在我的代码中获取引用变量的名称。我想要o/p作为哈利(这是我的参考变量)。这件事可能吗?获取参考变量的名称

代码:

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

     namespace ConsoleApplication1 
     { 
      class Program 
      { 
       static void Main(string[] args) 
       { 
        student harry = new student(); 
        //OUTPUT:harry 
       } 
      } 

      public class student { } 
     } 
+3

将'public'添加到字段定义 – Grundy

+0

您是否想要在代码中声明学生的姓名或变量的名称。 –

+2

作为一个节点,请花时间阅读关于C#的约定。例如,您的类名应该用PascalCase编写。如果你关注他们,它会让每个人都更容易,并且当你学习语言时更容易接受他们。 –

回答

1

没有没有办法做到这一点。您只能访问存储在班级中的数据。

你可以做的是比较参考例如

if(otherStudent == student) { } 

在这种情况下,你考天气变量otherStudent指向相同的对象变量student点。

1

更好地利用公共财产不是一个领域,并做到这一点是这样的:

//Class 

public class Student { public string Name { get; set; }} 

//Instantiate class method 1: 

Student harry = new Student() {Name = "Harry"}; 

//Instantiate class method 2: 

Student harry = new Student(); 
harry.Name="Harry"; 


//get property output: 


Console.WriteLine(harry.Name); 
+0

你使用'property'而不是字段:-) – Grundy

+0

是的。它是故意的:)。我想更好,但他可以选择。动态是一样的 –

+0

你也改变了领域的财产 –