【问题标题】:Can't use function in another function [duplicate]不能在另一个函数中使用函数[重复]
【发布时间】:2020-04-19 04:42:51
【问题描述】:

我不能在我的函数中使用函数“传输文件”

我必须在哪里进行更改?

函数应该是公共函数吗?还是只能在创建新类时使用其他功能?

namespace Webshopfiletransfer
{
    public partial class Webshopfiletransfer : ServiceBase
    {
        private static System.Timers.Timer aTimer;

        public Webshopfiletransfer()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            SetTimer();

            aTimer.Start();
        }

        private static void SetTimer()
        {
         // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(30000);
         // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {            
            transferfiles("download");
          //transferfiles("upload");
        }

        private void transferfiles(string modus)
        {
        }
    }
}

【问题讨论】:

    标签: c#


    【解决方案1】:

    您不能在静态方法中调用非静态方法。静态方法或属性只能调用同一类的其他静态方法或属性。

    当您定义静态方法或字段时,它无法访问为该类定义的任何实例字段,它只能使用标记为静态的字段。

    静态(C# 参考):here

    改变

    private void transferfiles(string modus)
    {
    
    }
    

     private static void transferfiles(string modus)
     {
    
     }
    

    或者你可以创建一个类的实例

     private static void OnTimedEvent(Object source, ElapsedEventArgs e)
     {
            Webshopfiletransfer webshopfiletransfer  = new Webshopfiletransfer();
            webshopfiletransfer.transferfiles("download");
            //transferfiles("upload");
     }
    

    【讨论】:

      【解决方案2】:

      您应该将transferfiles 方法标记为静态。

      private static void transferfiles(string modus)
      

      【讨论】:

        【解决方案3】:

        我不能在我的函数中使用函数“tranferfiles”。

        因为您的OnTimeEvent() 是静态函数,而您的transferfiles() 函数不是静态函数,请将transferfiles() 函数更改为静态。

        通过将 transferfiles() 函数更改为 static 将调用该函数而不创建其类的实例

        private static void transferfiles(string modus)
        {
           //Your code
        }
        

        From MSDN:

        静态方法和属性不能访问非静态字段和 事件在其包含类型中,并且它们无法访问实例 任何对象的变量,除非它在方法中显式传递 参数。

        【讨论】:

          【解决方案4】:

          私有函数只能在同一个类中使用。 如果你想在外面(从另一个班级)使用它,你必须把它改成公共的。

          另外检查已经提到的静态事物。无需实例化类中的对象即可使用静态函数。如果您不想创建对象,请将其更改为静态。 否则,从类中创建一个对象并从该对象调用 transferfiles。

          【讨论】:

          • private 的函数在这里无关紧要。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-03-07
          • 1970-01-01
          • 2020-06-12
          • 2016-09-20
          • 1970-01-01
          • 2017-05-24
          • 1970-01-01
          相关资源
          最近更新 更多