3

我收到以下错误:

在声明之前不能使用局部变量“dob”

这是我的实现

public class Person
    {
        ...
        public string dob { get; set; }
        ...

       public int getAge()
       {
                DateTime origin = DateTime.Parse(dob);
                return DateTime.Today.Year - origin.Year;
        }

        public string getFormattedDoB()
        {
                DateTime origin = DateTime.Parse(dob);
                string dob = origin.ToString("d");
                return dob;
        }
    }

我不知道该怎么做,因为它抱怨它使用了 dob ingetFormattedDoB()但不是在getAge()它之前。如果有人能对此有所了解,那就太好了

4

4 回答 4

10

您已经在 getFormattedDoB 中声明了一个名为 dob 的局部变量。编译器无法区分它和成员 dob 之间的区别。尝试在您的意思是成员变量而不是本地的地方添加“this”:

DateTime origin = DateTime.Parse(this.dob);

更好的是,不要为局部变量使用相同的名称。

编辑:除非您确实打算设置成员变量而不是创建新变量。在这种情况下,按照安德鲁的建议删除“字符串”。

于 2012-04-12T01:48:37.860 回答
4

The problem is that you have two dobs- the property and the local variable. The scope of a variable declaration (string dob = ...) is the whole block (everything between the { and }). Therefore the compiler thinks that on the line:

DateTime origin = DateTime.Parse(dob);

you are using the dob variable before it is declared, when (we assume) you really meant the dob property.

As others have mentioned, you should rename the property. The standard naming convention in C# would be

public String DateOfBirth { get; set; } 
//(assuming that is what DOB stands for)

or better yet

public DateTime DateOfBirth { get; set; } 
于 2012-04-12T01:49:15.593 回答
0

You have reused the variable name "dob" in getFormattedDoB as a local string, which is confusing the compiler. There are 2 possible solutions:

  1. Rename the local dob in getFormattedDoB (which you really should do because it's good practice).
  2. Use this.dob in the following line to specify the class level variable (which you should probably also do because it's also good practice:

    DateTime origin = DateTime.Parse(this.dob);

于 2012-04-12T01:48:58.283 回答
0

You are redeclaring dob in

string dob = origin.ToString("d"); 

it should be

 dob = origin.ToString("d"); 
于 2012-04-12T01:49:25.573 回答