从构造函数

时间:2018-03-01 14:56:01

标签: c#

有人可以帮助我如何获取字符串x的值并将其放到另一个类中吗?我想在另一个类中使用字符串x的值。

namespace WindowsFormsApp6
{
    public partial class Titles : Form
    {
        public Titles(string strToDisplay)
        {
            InitializeComponent();
            string x = strToDisplay;
        }

        private void titleList_SelectedIndexChanged_1(object sender, EventArgs e)
        {
           // USE X HERE
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您需要将参数存储在类字段中:

class Titles
{
    private string strToDisplayField;
    public Titles(string strToDisplay)
    {
        InitializeComponent();
        strToDisplayField = strToDisplay;
    }


    private void titleList_SelectedIndexChanged(object sender, EventArgs e)
    {
        var local = strToDisplayField; // Is accessible here
    }
}

答案 1 :(得分:1)

您无法访问该方法之外的方法范围变量。您需要在类级别声明该变量并重用它。

from Bio import SeqIO

fasta_dict = {record.id: record.seq for record in
              SeqIO.parse('Input.fasta', 'fasta')}

def yield_records():
    for record in SeqIO.parse('Input.fastq', 'fastq'):
        record.seq = fasta_dict[record.id]
        yield record

SeqIO.write(yield_records(), 'DesiredOutput.fastq', 'fastq')

答案 2 :(得分:1)

如果您想在课程中访问,请将x设为字段。

public class Titles
{
    private string x;
    public Titles(string strToDisplay)
    {
        InitializeComponent();
        this.x = strToDisplay;
    }

    private void titleList_SelectedIndexChanged(object sender, EventArgs e)
    {
        var newX = this.x;
    }
}

如果您想要在课堂外访问,请将x设为公共财产。

public class Titles
{
    public string X { get; set; }
    public Titles(string strToDisplay)
    {
        InitializeComponent();
        this.X = strToDisplay;
    }
}

public class AnotherClass
{
    private void titleList_SelectedIndexChanged(object sender, EventArgs e)
    {
        var t = new Titles("Some text");
        var newX = t.X;

    }
}