【问题标题】:Call a public bool as a public void将公共 bool 称为公共 void
【发布时间】:2016-05-31 09:34:48
【问题描述】:

我有一个问题,我想在公共类中做一个公共 bool 并将其称为 void。

我想检查第二个类中的布尔值是否为真。

例如在我的第一堂课:

public class GetWindow
{
   public string Check { get; set; } 

   public bool checkwindow()
   {
       if (Listofwindows.Contains(Check))
         return true;
       else
         return false;
   }
}

第二个:

public Form1()
{ [...]

  GetWindow myprogram1 = new GetWindow();
  myprogram1.Check = "Kin"; 

  if (myprogram1.checkwindow == true) 
        {/*Do thing*/}
}

显然它不起作用,因为 myprogram1.checkwindow 它说:

无法将方法组“checkwindow”转换为非委托类型 bool

“运算符'=='不能应用于'方法组'和'bool'类型的操作数

因为myprogram1.checkwindow == true。

所以这样做似乎死了,但我不知道如何以不同的方式做! (我需要我的 getwindow 类。)

【问题讨论】:

  • 您需要if (myprogram1.checkwindow() == true)。注意额外的一对括号。
  • 你忘了括号 () 我想:myprogram1.checkwindow() == true

标签: c#


【解决方案1】:

为了在C#中调用一个方法,你需要在方法名后面加上括号,即使方法不需要参数:

if (myprogram1.checkwindow() == true) 
{
        {/*Do thing*/}
}

此外,要评估布尔值,您无需与文字 true 进行比较。你可以写:

if (myprogram1.checkwindow()) 
{
        {/*Do thing*/}
}

【讨论】:

  • 好吧,当他们说“别忘了括号,我没想到这些。谢谢!!
【解决方案2】:

我将删除无用的属性并将参数传递给checkwindow 方法。像

public class GetWindow
{

   public bool checkwindow(string check)
   { 
       // Contains already returns true/false, no need of additional checks
       return Listofwindows.Contains(check);
   }
}

并用

调用它
public Form1()
{ [...]

    GetWindow myprogram1 = new GetWindow();
    if (myprogram1.checkwindow("Kin")) 
    {/*Do thing*/}
}

【讨论】:

    【解决方案3】:

    优化:

    public class GetWindow
    {
       public string Check { get; set; }   
       public bool checkwindow()
          {
             return Listofwindows.Contains(Check);
          }
    
    }
    

    然后调用它:

     GetWindow myprogram1 = new GetWindow();
     myprogram1.Check = "Kin"; 
    
    if (myprogram1.checkwindow()) 
    {
            {/*Do thing*/}
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 2017-07-25
      • 1970-01-01
      • 2012-09-14
      • 2017-02-21
      • 2011-07-11
      • 2020-09-22
      • 1970-01-01
      • 2012-04-29
      相关资源
      最近更新 更多