将来自不同类和方法的变量用于另一个类和方法

时间:2015-06-19 15:20:38

标签: c#

这是我的主要人物

public class Person
{
     public void SetAge(int n)
    {
         n = 20;
    }
    static void Main(string[] args)
    {

    }
}

我希望在这个继承的班级学生

中访问n variabe
 class student : Person
{

    public void GoToClasses()
    {
        Console.WriteLine("I am going to class");
    }
    public void ShowAge()
    {
        Console.WriteLine("My age is {0}",n);
    }
}

我尝试使用Person.n或SetAge(20)或SetAge(n),它不会工作!

6 个答案:

答案 0 :(得分:2)

public class Person
{
    public int Age {get; set;}
}

上面代表一个基本对象。

用例:

Person person = new Person();
person.Age = 25;

其他对象添加:

public class Person
{
    public Date BirthDate {get; set;}
    public int Age { get { return (DateTime.Now.Year - BirthDate.Year); } } //read only
}

答案 1 :(得分:2)

正如安德鲁所指出的那样,你没有一种方法可以访问该变量。不仅;类字段默认为私有访问。

链接:What are the Default Access Modifiers in C#?

Andrew为您编写的代码为您提供了一个属性,这并不是完全必要的,但它是获取getter和setter访问器方法的最简单方法。

如果您只希望继承的类具有访问权限,同时仍限制在类外部进行访问,请使用protected access modifier。

编辑:我误解了这个问题。你不仅不能从它使用的函数外部访问方法参数n,我甚至不确定你为什么要这样做。做安德鲁所说的,并对可变范围做一些研究。

答案 2 :(得分:1)

n不是Person的公开属性。您可以公开它或从int返回SetAge(int n)

曝光n:

public int n {get; set; }  

返回int:

public int SetAge(int n)
{
    // this is not the normal way to set via a method. you don't normally
    // set the input variable to a static value like this.
    n = 20;
    return n; 
}

答案 3 :(得分:0)

这是你的基类:

public class Person
{
    public int Age {get; set;}
}

这是你继承的类:

class student : Person
{
    public void ShowAge()
    {
        Console.WriteLine("My age is {0}",Age);
    }
}

答案 4 :(得分:0)

你必须声明" n"变量首先在Person类中。 试试这个:

public class Person
{
    public int n;
    public void SetAge()
    {
        n = 20;
    }

static void Main(string[] args)
   {

   }
} 

你不应该设置方法的参数" SetAge(int n)"当你以后更改此参数时。在这种情况下,它毫无意义。

答案 5 :(得分:0)

您应该将n变量声明为具有受保护或公开可见性的类字段。 像这样:

public class Person
{
    protected int n;

    public void SetAge(int n)
    {
         n = 20;
    }
}

或者你可以使用公共财产,因为其他答案已经显示

public class Person
{
    public int Age {get; set;}
}

这种方式在学生班中你可以像这样使用它

public class Student : Person
{
    public void ShowAge()
    {
        Console.WriteLine("My age is {0}", Age);
    }
}

或者像这样

public class Student : Person
{
    public void ShowAge()
    {
        Console.WriteLine("My age is {0}", n);
    }
}
相关问题