简体   繁体   English

Noob关注:制作新的无效方法的问题。 C#

[英]Noob Concern: Problems making a new void method. C#

I am trying to make a method in a new class that I made... 我正在尝试在我制作的新课程中制作一个方法......

public void CalcDrinks(bool HealthOption) 
{
    if (HealthOption)
    {
        CostOfBeverage = 5M; 
    }
    else
    {
        CostOfBeverage = 20M; 
    }
}

And I keep getting a red squiggly under the void saying... "expected class, delegate, enum, interface or struct error" 我一直在虚空之下得到一个红色的波浪形......“预期的类,代表,枚举,接口或结构错误”

I'm not sure what I am missing... 我不确定我错过了什么......

You would get that precisely that error if the method is declared outside of a class. 如果方法是之外声明的,那么你会得到那个错误。

namespace Blah
{
    public void CalcDrinks(bool HealthOption) 
    {
        if (HealthOption)
        {
            CostOfBeverage = 5M; 
        }
        else
        {
            CostOfBeverage = 20M; 
        }
    }
}

In this snippet, there is no class definition to be seen. 在此片段中,没有可见的类定义。 Fix it to the below and see that it compiles. 将其修复到下面并看到它编译。

public class Foo
{
    private decimal CostOfBeverage;

    public void CalcDrinks(bool HealthOption)
    {
        if (HealthOption)
        {
            CostOfBeverage = 5M;
        }
        else
        {
            CostOfBeverage = 20M;
        }
    }
}

Make sure the method is inside a class, and that the class/property/other method braces before and after the method line up. 确保方法在类中,并且类/属性/其他方法在方法排列之前和之后括起来。 Also make sure that the previous statement has a ; 还要确保前面的语句有; (semicolon). (分号)。

This problem normally occurs because you have mismatched braces before the method or you have a missing semi-colon: 出现此问题通常是因为您在方法之前有不匹配的大括号或者您的分号丢失:

Correct 正确

namespace A
{
    public class AA
    {
        public string B {get; set; }    
        public string C {get; set; }
        public void ShowD()
        {
            DoSomething;
        }

    }
}

Incorrect 不正确

namespace A
{
    public class AA
    {
        public string B { get; set; }      
        public string C {get; set;    // <--Note missing brace)
        public void ShowD()
        {
            DoSomething;
        }

    }
}

You're missing some code in your sample, but based on the error message, your function is declared outside of your class. 您在示例中缺少一些代码,但根据错误消息,您的函数在类之外声明。 The code for your method must be nested within your class. 您的方法的代码必须嵌套在您的类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM