Получение CS1502: лучшее совпадение перегруженного метода для <some_method> имеет недопустимые аргументы
В настоящее время у меня есть следующий код:
<%@ WebService Language="C#" Class="Notifications" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Script;
using System.Web.Script.Services;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
public class Notification
{
public int id;
public string text;
public Notification(int m_id, string m_text)
{
id = m_id;
text = m_text;
}
public Notification() {}
}
[System.Web.Script.Services.ScriptService]
public class Notifications : System.Web.Services.WebService {
List<Notification> Notification = new List<Notification>();
[WebMethod()]
public List<Notification> GetNotifications()
{
var notifications = new List<Notification>();
using (SqlConnection objSQLConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connString"]))
{
using (SqlCommand objSQLCommand = new SqlCommand("select * from table1 where col1 = @user", objSQLConnection))
{
objSQLCommand.Parameters.Add("@user", SqlDbType.VarChar, 5).Value = "abc";
objSQLConnection.Open();
using (SqlDataReader objSQLDataReader = objSQLCommand.ExecuteReader())
{
while (objSQLDataReader.Read())
{
notifications.Add(new Notification(objSQLDataReader["id"], objSQLDataReader["text"]));
}
}
}
}
return notifications;
}
}
Что дает мне следующую ошибку:
Compiler Error Message: CS1502: The best overloaded method match for 'Notification.Notification(int, string)' has some invalid arguments
На линии:
notifications.Add(new Notification(objSQLDataReader["id"], objSQLDataReader["text"]));
Кто-нибудь знает, почему это происходит?
4 ответа
Кажется, что некоторые функции отсутствуют, например, вы никогда не создаете объект Уведомления. Если вы используете неявно созданные переменные в VB, это, скорее всего, не сработает для преобразования в C# (и в VB также не рекомендуется). Кроме того, я бы посоветовал вам использовать Using
блоки, чтобы убедиться, что все закрыто и правильно расположено:
<WebMethod()> _
Public Function GetNotifications() As List(Of Notification)
Dim notifications As New List(Of Notification)()
Using connection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"))
Using command = New SqlCommand("select * from table1 where col1 = @user", connection)
command.Parameters.Add("@user", SqlDbType.VarChar, 5).Value = sUser;
connection.Open()
Using reader = command.ExecuteReader()
Dim idIndex As Integer = reader.GetOrdinal("id")
Dim textIndex As Integer = reader.GetOrdinal("text")
While reader.Read()
notifications.Add(New Notification(reader.GetInt32(idIndex), reader.GetString(textIndex)))
End While
End Using
End Using
End Using
Return notifications
End Function
Теперь он должен (в идеале) преобразовать в:
[WebMethod()]
public List<Notification> GetNotifications() {
var notifications = new List<Notification>();
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connString"])) {
using (SqlCommand command = new SqlCommand("select * from table1 where col1 = @user", connection)) {
command.Parameters.Add("@user", SqlDbType.VarChar, 5).Value = sUser;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader()) {
int idIndex = reader.GetOrdinal("id")
int textIndex = reader.GetOrdinal("text")
while (reader.Read()) {
notifications.Add(new Notification(reader.GetInt32(idIndex), reader.GetString(textIndex)));
}
}
}
}
return notifications;
}
Редактировать:
Изменения сделаны:
- Изменено в скобках при доступе
AppSettings
- Изменено в скобках при доступе
objSQLDataReader
- Изменен код читателя для использования
GetOrdinal
,GetInt32
а такжеGetString
- Изменены имена переменных; удалены венгерские обозначения
Проблема в доступе к коду vb AppSettings
(и массивы в целом), как:
AppSettings("keyname")
и C# делает массивы как:
AppSettings["keyname"]
Конвертеру иногда трудно определить разницу между массивом и функцией.
Ну, очевидно, код был правильно преобразован - только используемые переменные не были объявлены в VB, поэтому они также не объявлены в коде C#. Следующее должно работать лучше:
[WebMethod()]
public List<Notification> GetNotifications()
{
// Have a look at the code conventions - variable names should not start
// with a capital letter...
List<Notification> Notifications = new List<Notification>();
SqlConnection objSQLConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"));
SqlCommand objSQLCommand = new SqlCommand("select * from table1 where col1 = @user", objSQLConnection);
objSQLCommand.Parameters.Add("@user", SqlDbType.VarChar, 5).Value = sUser;
objSQLCommand.Connection.Open();
SqlDataReader objSQLDataReader = objSQLCommand.ExecuteReader();
while (objSQLDataReader.Read()) {
Notifications.Add(new Notification(objSQLDataReader("id"), objSQLDataReader("text")));
}
objSQLDataReader.Close();
objSQLCommand.Connection.Close();
return Notifications;
}
О, и не забудьте добавить соответствующие using
заявления!
РЕДАКТИРОВАТЬ
Сделал еще одно изменение в коде - Notifications
нигде не объявлено.
Конвертер VB в C# (и другие) от DevelopFusion - это бесплатная услуга, предоставляемая вам бесплатно. Это руководство. Большая часть кода, который вы представили, является функциональной, и вам только сейчас нужно потратить десятую часть времени на исправление нескольких мелких проблем с вашим кодом (кстати, приведенный выше код синтаксически корректен... если вы объявили необъявленные переменные * подсказка *). В частности, вам нужно объявить objSQLCommand
а также objSQLDataReader
если вы еще не сделали это в другом месте:
SqlCommand objSQLCommand;
SqlDataReader objSQLDataReader;