【问题标题】:Second method cant use variable of property第二种方法不能使用属性变量
【发布时间】:2018-10-16 08:41:02
【问题描述】:

我对这个东西很陌生,所以我可能有一个基本的误解,我希望有人能帮我解开。我一直在寻找类似的主题,但没有找到明确的答案。

代码:

namespace ConsoleApp37
{
    class Propertything
    {
        public int number1 = 5;
        public int test
        {
            get { return number1; }
            set { number1 = value; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Propertything x = new Propertything();
            Console.WriteLine("{0}", x.number1);
            x.number1 = 25;
            Console.WriteLine("{0}", x.number1);
            Console.ReadKey();
        }
    }
    class SecondMethod
    {
        public void Method2(string[] args)
        {
            SecondMethod y = new SecondMethod();
            Console.WriteLine("{0}", y.number1);
            y.number1 = 33;
            Console.WriteLine("{0}", y.number1);
            Console.ReadKey();
        }
    }
}

问题是由于这些行(编号 1)而导致的 CS1061 错误:

Console.WriteLine("{0}", y.number1);
y.number1 = 33;
Console.WriteLine("{0}", y.number1);

我的想法是,一个属性(第一个类)用于多个类使用相同变量的情况。 我预计结果会说:5 25 5 33。

有人可以解释为什么第二类 (class SecondMethod) 不能像类 Program 一样使用变量 number1 吗?

【问题讨论】:

  • 这对我来说毫无意义。 y 的类型为 SecondMethod,没有 number1 属性。
  • 首先:不要打电话给你的班级 ...Method。第二:您的SecondMethod-class 不知道number1 的任何内容,它在PropertyThing 中声明。为什么你认为这两个班级彼此了解?
  • SecondMethod y = new SecondMethod();,你自己创建了一个实例类。要使用它,您需要使用 Propertything y = new Propertything();
  • 我不知道我怎么会错过我看了那东西 20 分钟的那部分。我很困惑

标签: c# class properties


【解决方案1】:

因为number1 属性在Propertything 中,而不在SecondMethod 中。

你创造

SecondMethod y = new SecondMethod();
Console.WriteLine("{0}", y.number1);

不像在main方法中,

Propertything x = new Propertything();
Console.WriteLine("{0}", x.number1);

您可以在Method2 中使用Propertything 或添加属性

public int number1;

SecondMethod

【讨论】:

  • 哦,谢谢,我完全忽略了这两种方法之间的区别。
【解决方案2】:

这是因为您的类 SecondMethod 不包含名称为 number1 的变量或属性

class SecondMethod
{
    public void Method2(string[] args)
    {
        SecondMethod y = new SecondMethod();
        Console.WriteLine("{0}", y.number1);
        y.number1 = 33;
        Console.WriteLine("{0}", y.number1);
        Console.ReadKey();
    }
}

它在你的另一个班级里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多