【问题标题】:How to initialize reference in class?如何在类中初始化引用?
【发布时间】:2017-04-14 05:28:57
【问题描述】:

我需要这样的东西

public class Displayer
{
    public ref string[] lines { get; set; }
}

但我没有找到任何解决方案。 我的“应用程序”的完整代码是:

 public class Displayer
{
    public ref string[] lines { get; set; }
    public async void Update()
    {
        while(true)
        {
           Console.Clear();
           foreach(string s in lines)
           {
              Console.WriteLine(s);
           }
        }
    }
}   

【问题讨论】:

  • 为什么你认为你需要一个参考?你觉得它会给你什么?您希望如何使用它?
  • @ClickRick,我需要使用异步方法来显示更改,这是通过更改 int[] 变量来完成的。
  • 然后添加代码来说明这一点。哦,不带参考试试看。
  • @ClickRick,已更新
  • @M.kazemAkhgary,谢谢,但这只是示例代码。我只是不知道如何将引用变量添加到类。

标签: c# ref


【解决方案1】:

这是完全错误的。您的 Displayer 类一遍又一遍地不必要地更新控制台。每秒千次。这不合逻辑。

正确的方法是在需要时更新控制台。您的属性需要以另一种方式实现。

public class Displayer
{
    private string[] _lines;

    public string[] Lines
    {
        get { return _lines; }
        set
        {
            // while setting new value call Update
            _lines = value;
            Update();
        }
    }

    public async void Update()
    {
        // update console only once
        Console.Clear();

        foreach (string s in Lines)
        {
            Console.WriteLine(s);
        }
    }
}

如果您想了解收藏中的变化,请改用ObservableCollection

您无需在此处更改引用。因为您可以随时更改集合的大小。

public class Displayer
{
    public Displayer()
    {
        Lines = new ObservableCollection<string>();
        Lines.CollectionChanged += Update; // Update will be called automatically when ever collection changes.
    }

    public ObservableCollection<string> Lines { get; }

    private void Update(object sender, NotifyCollectionChangedEventArgs args)
    {
        // update console only once
        Console.Clear();

        foreach (string s in Lines)
        {
            Console.WriteLine(s);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 2021-03-23
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多