【问题标题】:Calling a variable and list to another class?将变量和列表调用到另一个类?
【发布时间】:2019-10-15 02:47:36
【问题描述】:

我正在学习 c#,但偶然发现了一个问题。我试过在谷歌上环顾四周,将变量调用到另一个类上。我发现是通过使用 get set 方法。这是唯一的方法吗?

另一个问题是,我如何从列表中检索信息以打印到另一个类。

我做的代码可以在下面找到。

class Program
{
    public int Xyz { get; set; } = 15;

    public static void Main()
    {
        Console.WriteLine("Hello World");

        List<int> Lst = new List<int>();

        Lst.Add(1);
        Lst.Add(2);
        Lst.Add(3);

        for (int x = 0; x < Lst.Count; x++)

        {
            Console.WriteLine("This is number {0}.", Lst[x]);
        }
    }

    public class Tests
    {
        public void Next(int Xyz)
        {
            Console.WriteLine("Value of Xyz is: {0}", Xyz);
            Console.WriteLine("{0}", Lst.Count);
            List<int> Lst2 = new List<int>(Lst);
            Console.WriteLine("Lst2 has {0} values.", Lst2.Count);
        }
    }

}

我想从中看到什么

Console.WriteLine("Value of Xyz is: {0}", Xyz);是值 15。

Console.WriteLine("{0}", Lst.Count); 值 3。

非常感谢!

【问题讨论】:

  • mjwills的方法还可以。我通过使用静态类 PublicZoom 提供了另一种方法。看我的回答。

标签: c# variables


【解决方案1】:
using System.Collections.Generic;
using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        PulicZoom.Lst.Add(1);
        PulicZoom.Lst.Add(2);
        PulicZoom.Lst.Add(3);

        for (int x = 0; x < PulicZoom.Lst.Count; x++)

        {
            Console.WriteLine("This is number {0}.", PulicZoom.Lst[x]);
        }

        Tests test = new Tests();
        test.Next();
    }

    public class Tests
    {
        public void Next()
        {
            Console.WriteLine("Value of Xyz is: {0}", PulicZoom.Xyz);
            Console.WriteLine("{0}", PulicZoom.Lst.Count);
            List<int> Lst2 = new List<int>(PulicZoom.Lst);
            Console.WriteLine("Lst2 has {0} values.", Lst2.Count);
        }
    }

    public static class PulicZoom
    {
        public static int Xyz { get; set; } = 15;
        public static List<int> Lst = new List<int>();
    }

}

【讨论】:

  • 嗨,Charles,我已经实现了修改后的代码,我必须说,当我要调用的变量和列表在另一个类中声明时,它看起来更清晰。非常感谢您的代码。这正是我想要的。
  • @Nate 随时准备提供帮助。如果你接受我的回答,那就更好了。
  • 我认为这里需要一些解释,即使它是答案。这如何解决问题?多一点解释确实会提高您的回答质量。
【解决方案2】:

首先,您应该了解基本的面向对象概念,包括变量的范围。请注意,您的 Lst 是在函数“main”中创建的。这意味着名称“Lst”仅在此函数中有效。由于您的 Tests 类存在于函数之外,因此它无法访问该变量。

此外,您在测试中定义了函数 Next(int xyz)。首先,这个 xyz 将隐藏外部 xyz 的名称,因为它们共享相同的名称。这意味着每当您引用 xyz 时,您只是引用作为变量传递给函数的 xyz,而不是外部的 xyz。此外,该函数永远不会在任何地方调用。因此,它不会运行。由于该函数位于测试类中,因此您需要先使用“Test t = new Test();”创建测试对象的实例,然后使用“t.Next();”调用该函数

【讨论】:

  • 嗨,Arch,我会这样做,因为我还在学习。感谢您解释我的错误!
猜你喜欢
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
相关资源
最近更新 更多