是否可以使用母亲的对象字段而不在方法的参数中传递它们

本文关键字:参数 方法 可以使 母亲 对象 字段 是否 | 更新日期: 2023-09-27 18:32:51

假设我们有2个类:

public class object1
{
string hehe = "xd";
void function()
   {
   if (x != 5) {} // here!
   }
}
public class object2
{
int x;
int y;
object1 z;
}

我想在对象 1 中的方法中使用 x(来自对象 2),该方法存储在对象 2 中。这可能吗?我知道,我可以用方法参数传递数据,但我想知道是否有可能以某种方式避免这种情况

是否可以使用母亲的对象字段而不在方法的参数中传递它们

要访问另一个类中的属性,您需要传递对象的即时或值本身。或者,如果属性是静态的,则可以在类定义上访问它。您还需要考虑为字段、属性和方法显式指定访问修饰符,以便它们更加"可见"。

public class ClassOne
{
    public static int MyStaticInteger { get { return 1; } }
    public int x { get; set; }
    public int y { get; set; }
}
public class ClassTwo
{
    public const string hehe = "xd";
    public void doSomething(ClassOne myOtherClass)
    {
        if (myOtherClass.x != 5)
        {
        }
        if (ClassOne.MyStaticInteger != 5)
        {
        }
    }
}