【问题标题】:How can i call a method from form1 to a new class without making the method in form1 static?如何在不使 form1 中的方法静态的情况下将方法从 form1 调用到新类?
【发布时间】:2014-07-15 13:41:15
【问题描述】:

并且也没有在新类中创建新的 form1 实例。 在 form1 中,我有一个公开的方法:

public void Test()
{

}

那么这个类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Timers;
using System.Windows.Forms;

namespace ScrollLabelTest
{

    class SaveOldHtml
    {
        private static Form frm1 = null;
        private static int count;
        private static System.Timers.Timer _timer = new System.Timers.Timer();
        private static string page;
        private static List<string> newText = new List<string>();

        public SaveOldHtml(string DirectoryToSave,int count, string contents)
        {
            System.IO.File.WriteAllText(DirectoryToSave + "Page" + count.ToString("D6")
                                        + ".html", contents);
        }

        public SaveOldHtml(string DirectoryToSave, List<string> newTextList, int count)
        {
            using (StreamWriter myStream = new StreamWriter(DirectoryToSave + "newTextList" + count.ToString("D6")
                                        + ".txt"))
            {
                for (int i = 0; i < newTextList.Count; i++)
                {
                    myStream.WriteLine(newTextList[i]);
                }

            }
        }

        public static void Start(Form1 form)
        {
            frm1 = form;
            _timer.Elapsed += _timer_Elapsed;
            _timer.Interval = 10000;
            count = 5;
            LoadOldHtmlFiles();
            _timer.Start();
        }

但是 frm1 不具有来自 form1 的方法的属性。 我需要在此类 form1 中创建新实例吗?或者有没有其他方法不做实例,不做静态方法?

【问题讨论】:

  • 为什么你不想创建表单的实例?你的表单已经打开了吗?
  • 不清楚您要达到的目标。无论如何,我认为在 Forms 中有公共方法供其他类调用并不是一个好主意。

标签: c# .net winforms


【解决方案1】:

您将构造函数中的参数存储为基本类型 Form 而不是实际类型 Form1。

改变

private static Form frm1 = null;

private static Form1 frm1 = null;

frm1.Test() 将可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多