无法在非静态上下文中访问静态方法

时间:2018-05-29 04:06:26

标签: c# function methods static-methods

我刚刚开始参加C#编程的中级课程,并且我正在学习如何创建多个类并创建在我的程序中使用的方法。

对我来说这是一个非常新的主题,所以如果它是非常明显或愚蠢的话,我会道歉。我在所有方法中都得到了以下信息:

Cannot access static method in non-static context

方法类中的代码:

public static int Add(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum += n;
        }

        return sum;
    }

    public static int Subtract(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum -= n;
        }

        return sum;
    }

    public static int Multiply(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum *= n;
        }

        return sum;
    }

    public static int Divide(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum /= n;
        }

        return sum;
    }

    public static string[] CheckingOfSomeSort(string userInput, int value, bool isAddition, bool isSubtraction, bool isDivision, bool isMultiplication) {
        if (userInput.Contains("+")) {
            var addition = userInput.Split('+');
            value = 1;
            isAddition = true;
            return addition;
        } else if (userInput.Contains("-")) {
            var subtraction = userInput.Split('-');
            value = 2;
            isSubtraction = true;
            return subtraction;
        } else if (userInput.Contains("*")) {
            var multiplication = userInput.Split('*');
            value = 3;
            isMultiplication = true;
            return multiplication;
        } else if (userInput.Contains("/")) {
            var division = userInput.Split('/');
            value = 4;
            isDivision = true;
            return division;
        }

        return null;
    }

我正在尝试创建一个计算器(我已经完成了,但是我现在尝试使用方法)

3 个答案:

答案 0 :(得分:5)

根据你的评论,我知道你正在创建一个CalculatorMethods的对象,并且你正在尝试使用这个对象来调用该类的静态方法。

我对问题的评论:

  

这些方法都是静态的。 (以及它们的使用方式也应该是静态的)。但是静态方法不能使用Class的对象访问,而是直接使用类的类型。这里我猜测CalculatorMethods是哪种方法的类,你会尝试做一些像calc.Add()..这是不可能的。而是做CalculatorMethods.Add()

相反,您可以通过直接调用类似belwo,

来尝试
    void MethodOfCalling()
    {
        int sum = CalculatorMethods.Add(new int[2] { 1, 2 });
    }

你可以看到,我使用CalculatorMethods(类名 - 更恰当地说类的类型)来调用方法而不是类的对象。

答案 1 :(得分:3)

@MrSanfrinsisco,欢迎来到C#编程。正如你要求它很容易调用静态方法。按照以下步骤拨打电话

1)创建1个类文件。让我们说它的Calculations.cs [把你的代码放在这个类中]你的班级的最后一个封面将是..

ReportProblem

2)然后转到您要访问该方法的页面并简单地写入。例如,如果您想在default.aspx上使用它,请使用以下方法。 [注意:你必须在这里给你的类的名称空间,然后只有你能够使用WebApplication3.Models在我的例子中访问这个类;]

import UIKit
import StoreKit
import MessageUI

class SettingTVController: UITableViewController, MFMailComposeViewControllerDelegate {

var settingTitleConnection = showData()

override func viewDidLoad() {
    //skip
}

override func didReceiveMemoryWarning() {
   //skip
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   //skip
}

override func numberOfSections(in tableView: UITableView) -> Int {
    //skip
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   //skip
}



override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if tableView.indexPathForSelectedRow?.row == 2 && tableView.indexPathForSelectedRow?.section == 1 {
        orderOfSendAnEmailToReportTheProblem()
    } else {
      //skip
    }

    tableView.deselectRow(at: indexPath, animated: true)
}

//-----<The codes below is used to construct the function of reporting problem with email>-----
func orderOfSendAnEmailToReportTheProblem() {
    let mailComposeViewController = configureMailController()
    self.present(mailComposeViewController, animated: true, completion: nil)
    if MFMailComposeViewController.canSendMail() {
        self.present(mailComposeViewController, animated: false, completion: nil)
    } else {
        showMailError()
    }
}
//Activate the series of the commands of sending the email.

func configureMailController() -> MFMailComposeViewController {
    let mailComposeVC = MFMailComposeViewController()
    mailComposeVC.mailComposeDelegate = self

    mailComposeVC.setToRecipients(["datototest@icloud.com"])
    mailComposeVC.setSubject("Reporting of Problems of Rolling")

    return mailComposeVC
}
//Set the recipient and the title of this email automatically.

func showMailError() {
    let sendMailErrorAlert = UIAlertController(title: "Could not send the email.", message: "Oops, something was wrong, please check your internet connection once again.", preferredStyle: .alert)
    let dismiss = UIAlertAction(title: "Ok", style: .default, handler: nil)
    sendMailErrorAlert.addAction(dismiss)
    self.present(sendMailErrorAlert, animated: true, completion: nil) //If you conform the protocol of NSObject instead of UIViewController, you could not finish this line successfully.
}
//Set a alert window so that it would remind the user when the device could not send the email successfully.

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)
    //UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: true, completion: nil)
}
//Set this final step so that the device would go to the previous window when you finish sending the email.
//-----<The codes above is used to construct the function of reporting problem with email>-----
}

this是调用此类方法的基本注释。

让我知道你还需要任何帮助。 :)

答案 2 :(得分:0)

要调用静态方法,您需要从它定义的类中引用它,而不是该类的实例。 例如:

Calculator.Divide(); // works 


Calculator obj = new Calculator(); 
obj.Divide(); // Not works

NOTE : Divide() is a static method