[英]Cannot implicitly convert type 'void' to 'int'?
好的,所以我对编程还很陌生,我不知道为什么会收到此错误。
我的方法应该存储在此方法中执行的邮件:
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的解决方案。 也许不可能吗?
我的问题是:如何在代码中转换这些类型?
请不要苛刻,我真的很陌生。 感觉就像我在信息海洋中畅游,不知道在哪里寻找或开始。 因此,任何建议的教程都非常欢迎。
方法
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;
}
制作方法时,您定义返回类型。 无效意味着它将不返回任何东西。 您已将方法定义为public void StoreMail()
,因此说它不会返回任何内容。 调用该方法时,您要求返回phishingMailId = _storageAgent.StoreMail(phishingMail)
。 但是因为您将该方法定义为void,并且没有让该方法返回任何内容,所以您无法获取ID,并且会收到错误消息。
要解决此问题,您将必须使您的方法返回一个int
public int StoreMail(PhishingMail phishingMail){}
然后在方法中进一步定义要返回的内容
return newId;
以我为例,我在数据库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-最后,您可以从程序中调用类和存储过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.