局部变量声明问题 [英] Local Variable Declaration Issue

查看:212
本文介绍了局部变量声明问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时得到以下错误:

声明之前不能使用局部变量DOB

Cannot use local variable 'dob' before it is declared

下面是我执行

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;
        }
    }



我不知道是怎么打的,是因为它在抱怨它在 getFormattedDoB使用的DOB(),但不是在 getAge()面前有来。如果任何人都可以在此提供一些线索,这将是巨大的。

I am not sure what to make of this because it is complaining about it's use of dob in getFormattedDoB() but not in getAge() which comes before it. If anyone could shed some light on this that would be great

推荐答案

您已经声明在getFormattedDoB一个局部变量叫DOB。编译器不能告诉大家,和成员出生日期之间的差异。尝试添加本在这里你的意思是成员变量而非本地:

You've declared a local variable in getFormattedDoB called dob. The compiler can't tell the difference between that and the member dob. Try adding "this" where you mean the member variable rather than the local:

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



更​​妙的是,不要使用本地变量的名称相同。

Better still, don't use the same name for the local variable.

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

Unless you did actually intended to set the member variable and not create a new one. In which case remove the "string" as Andrew suggested.

这篇关于局部变量声明问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆