属性在当前上下文中不存在 [英] Property does not exist in the current context

查看:53
本文介绍了属性在当前上下文中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

属性在当前上下文中不存在".

"Property does not exist in the current context".

我在 StackOverflow 上检查了导致这种情况的常见原因,但我没有犯任何一个错误.(至少我理解的那些都没有^^).我正在使用 Microsoft Visual Studio 2015

I checked on StackOverflow the usual causes of this, but I have made no one of the mistakes presented. (at least none of those I understood ^^). I am working with Microsoft Visual Studio 2015

这是我的代码:

namespace ConsoleApplication5
{
    public class Voiture
    {
        public int Vitesse { get; set; }
        public Voiture()
        {
            Vitesse = 5;
        }
        public string Marque
        {
            get
            {
                throw new System.NotImplementedException();
            }

            set
            {
            }
        }
    }
}

在另一个文件中

namespace ConsoleApplication5
{
    public class Audi : Voiture
    {
        public void Deraper()
        {
            Console.WriteLine("Vroooouum !!");
        }

        this.Marque = "Audi";
    }
}

如果我使用 Voiture.Marque 而不是 this.Marque,我会遇到同样的问题.如您所见,命名空间没有问题.知道发生了什么吗?

If instead of this.Marque I use Voiture.Marque, I get the same problem. As you can see, the namespaces are OK. Any idea of what is going on ?

推荐答案

1) 不允许在方法主体之外访问和初始化继承的属性.您只能在那里声明新的属性或字段.

1) You are not allowed to access and initialize inherited properties outside a method body. You are only allowed to declare new properties or fields there.

2) Marque 属于 int 类型,您不能为其分配 string

2) Marque is of type int and you cannot assign a string to it

3) 你的 Marque 的 setter 是空的,所以这不会有任何影响

3) your setter of Marque is empty so this will have no effect

解决方案:

1) 将 this.Marque 的访问移到构造函数或方法体中!

1) Move the access of this.Marque into the constructor or a method body!

2) 将 Marque 的类型更改为 string 或您分配给它的值给 int

2) change either the type of Marque to string or the value that you assign to it to an int

3) 添加一个额外的私有字段并按以下方式重写 setter(和 getter):

3) add an extra private field and rewrite the setter (and the getter) in the following way:

private int marque;
public int Marque
{
    get
    {
        return marque;
    }

    set
    {
        marque = value;
    }
}

有关如何使用属性的更多信息,您可以查看以下链接:

https://www.dotnetperls.com/property

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties

如果我使用 Voiture.Marque 而不是 this.Marque,我会遇到同样的问题.

If instead of this.Marque I use Voiture.Marque, I get the same problem.

这是因为第一个问题仍然有效.如果您在方法主体内执行此操作,则会遇到额外的问题!因为Marque 不是static,所以你不能通过用类名调用它来使用它.您需要一个 Voiture

This is because the first problem is still valid. If you would do this inside a method body you would get an additional problem! Because Marque is not static, so you cannot use it by calling it with the class name. You would need an instance of an object of type Voiture

这篇关于属性在当前上下文中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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