在另一个类(不在方法或函数中)调用类时获取错误

时间:2016-01-05 17:42:46

标签: c#

我做了两节课 第一个Input.cs

public class Input
{


}

我试图在inputsevice.cs中调用输入类

second inputsevice.cs

public class InputService
{
    Input test= new Input();
    test// error (I can't use this field)
}

我找不到输入字段{input是一个字段但是使用类型}

2 个答案:

答案 0 :(得分:0)

您不能对成员声明语句中的属性执行任何操作(这样做没有意义)。但是你可以在类的任何方法中访问它:

public class Input
{
    public int name { get; set; }

    public void SomeMethod()
    {
        // you can access "name" here
    }
}

答案 1 :(得分:0)

这就是你使用它的方式

//Class should have certain publicly accessible properties or methods to access from other classes.
    public class Input
    {
        private int x = 5;
        public string MyInput {get; set;} //Publicly accessible property
        public void DisplayInput()  //Publicly accessible method
        {
             Console.WriteLine(MyInput);
             Console.WriteLine(x);
        } 
    }        


    public class InputService
    {
        Input test= new Input(); //Object initialization

        InputService()   //Constructor
        { 
            //Properties and methods can be accessed in methods. 
            test.MyInput = "Hello World!";  
            //test.x   you can't access x because it is private.
            test.DisplayInput();

        }

    }
  

<强>输出:

     

Hello World!

     

5