【发布时间】: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