【问题标题】:use attribute of a method into another method将方法的属性用于另一个方法
【发布时间】:2011-06-01 03:23:25
【问题描述】:

如何将一个方法的属性用于另一个方法?

例如: (我在相关行中发表了评论)

我有

    public int merge()
    {

        string[] source = textBox3.Text.Split(',');

        int[] nums = new int[source.Length];//i want to use nums in mergesort() too,how can i do that?

        for (int i = 0; i < source.Length; i++)
        {
            nums[i] = Convert.ToInt32(source[i]);
        }
            }

  public int mergesort()
    {
        if (nums.Length > 1)///i wrote nums here but compiler doesnt know what nums is.
        {
            int n = nums.Length;
            int p = (int)Math.Floor(n / 2.0);
            int m = n - p;
            List<int> lst1 = new List<int>();
            lst1.AddRange(nums.Skip(n / 2));

            List<int> lst2 = new List<int>();
            lst2.AddRange(nums.Take(n / 2));
  }

【问题讨论】:

标签: c# variables parameters methods


【解决方案1】:

在类级别的私有变量/属性中定义 int[] nums

private int[] nums = null;

 public int merge() 

  {       
      string[] source = textBox3.Text.Split(','); 
       nums = new int[source.Length];//i want to use nums in mergesort() too,how can i do that?       
        for (int i = 0; i < source.Length; i++)    
           { 
               nums[i] = Convert.ToInt32(source[i]);
           }


    }

现在在归并排序函数中使用 nums。

【讨论】:

  • @arash:在这个例子中,nums 是一个“字段”
【解决方案2】:

public int mergesort(int[] nums)
{
    // ...
}

这似乎是问题所在。

【讨论】:

  • 我想使用merge()中存在的nums,而不是新的nums
  • 这些方法属于同一个类吗?
  • @arash:将 nums 声明为参数不会创建任何新的 nums。你应该了解[参数](en.wikipedia.org/wiki/Parameter_(computer_science%29),因为它们是编程中非常重要的概念
  • 好的,你可以在 merge() 方法中调用 mergesort(nums) 没有问题。包含该数组的值将毫无问题地传输到目标方法。
【解决方案3】:

虽然类级变量为您工作,但我建议将nums 作为参数发送到mergesort,因为最终的重构可能会决定排序在另一个类中。

public int mergesort(int[] nums)
{
    ...
}

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2019-03-29
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多