您能否在另一类类中的方法中获得变量值

  • 本文关键字:方法 变量值 一类 c# methods view
  • 更新时间 :
  • 英文 :


我是C#的新手,我一直坚持尝试获取一个方法中的变量值,该方法来自另一类的特定类中。

例如假设A类具有一种方法setPath ();,该方法具有称为字符串rootpath = "something";

的变量

我可以从另一个类带这个变量的rootpath;B类?!

任何帮助都非常感谢

您可以从该方法中 return。或者,如果它确实是必要的,则可以将其传递给refout参数。

  //your official method
  void setPath()
  {
    string rootPath = "Something";
  }
  // you can return a string
  string setPathByReturn()
  {
    string rootPath = "Something";
    return rootPath;
  }
  //or pass it to an out paramter
  void setPathByOut(out string str)
  {
    string rootPath = "Something";
    str = rootPath;
  }
  //or pass it to a reference
  void setPathByRef(ref string str)
  {
    string rootPath = "Something";
    str = rootPath;
  }

您应该注意的一件事,如果您通过ref参数传递字符串,则应在初始初始化。

用法的示例:

string striWithOut;
setPathByOut(out striWithOut);
string strWithRef = "";
setPathByRef(ref strWithRef);

您可以在MSDN上阅读有关refout参数通行证的更多信息。

  • 参考
  • OUT

不,你不能。实现这一目标的一种方法是使变量成为班级的公共财产。请参阅以下示例:

class A {
    public string rootpath { get; private set; }
    public void setPath()
    {
        this.rootpath = "something";
    }
}

现在,可以使用instanceOfA.rootpath从其他类访问该属性(而instanceOfA是您类的实例A(

最新更新