无法将类型'void'隐式转换为'int'吗?

问题描述 投票:1回答:3

好吧,我对编程还很陌生,我不明白为什么会收到此错误。

我的方法应该存储在此方法中执行的邮件:

    public void StoreMail(PhishingMail PhishingMail)
    {
        using (var phishingMailStorage = new PhishFinderModel())
        {
            phishingMailStorage.PhishingMail.Attach(PhishingMail);

            phishingMailStorage.SaveChanges();

        }

然后在我的processPhishingMail方法中,它调用Store方法。但是然后我得到一个错误:无法将类型'void'隐式转换为'int'。

public void ProcessPhishingMail(PhishingMail phishingMail)
{                     
      Hashtable phishingUrls;
      int phishingMailId;
      int phishingUrlId;
      //Error convertion
      phishingMailId = _storageAgent.StoreMail(phishingMail);

所以我无法真正找到从void转换为int的解决方案。也许不可能吗?

我的问题是:如何在代码中转换这些类型?

请不要苛刻,我真的很陌生。感觉就像我在信息海洋中畅游,不知道在哪里寻找或开始。因此,任何建议的教程都非常受欢迎。

c# entity-framework int void
3个回答
4
投票

方法

public void StoreMail(PhishingMail PhishingMail)

不返回任何值。因此,当您这样做时:

phishingMailId = _storageAgent.StoreMail(phishingMail);

由于StoreMail被声明为void,因此没有返回任何内容,您将收到此错误。

要解决此问题,只需像这样调用StoreMail

_storageAgent.StoreMail(phishingMail);

如果要从StoreMail返回值,则必须将其更改为返回int值:

public int StoreMail(PhishingMail PhishingMail)
{
    using (var phishingMailStorage = new PhishFinderModel())
    {
        phishingMailStorage.PhishingMail.Attach(PhishingMail);

        phishingMailStorage.SaveChanges();
    }

    return someIdWhichYouNeedToFigureOut;
}

4
投票

制作方法时,您定义返回类型。无效意味着它将不返回任何东西。您已将方法定义为public void StoreMail(),因此说它不会返回任何内容。调用该方法时,您要求返回phishingMailId = _storageAgent.StoreMail(phishingMail)。但是因为您将该方法定义为void,并且没有让该方法返回任何内容,所以您无法获得ID并得到错误。

要解决此问题,您必须使您的方法返回一个整数

public int StoreMail(PhishingMail phishingMail){}

然后在方法中进一步定义要返回的内容

return newId;

0
投票

就我而言,我是在数据库SQL Server中创建存储过程的,然后我在C#程序中创建了一个类,并调用了该存储过程,并在该类内部的存储过程中添加了参数,并返回了数据表中的数据,最后我可以在程序中的任何位置调用我的类了像这个例子:

1-创建存储过程:

CREATE proc [dbo].[GET_SAMPLE_KIND]
@TESTID int
as 
select Dept_id,ID_sample from LabTests
where LabTests.TestId = @TESTID 

2-在您的C#程序中创建类,并使用诸如以下代码的参数来调用存储过程:

public DataTable GET_SAMPLE_KIND(int TESTID)
        {
            DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
            DataTable dt = new DataTable();

            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@TESTID", SqlDbType.Int);
            param[0].Value = TESTID;

            dt = DAL.SelectData("GET_SAMPLE_KIND", param);
            DAL.close();
            return dt;
        }

要连接并从数据库读取数据,您必须使另一个类与sql server联系,在我的情况下,该类是DAL.selectData方法以从数据库中选择数据,对于插入,更新和删除语句,您还可以创建存储过程,然后在其中创建另一个void您的类的功能。

3-最后,您可以从程序中调用类和存储过程。

© www.soinside.com 2019 - 2024. All rights reserved.