Собственно у DXMenuItem есть конструктор с параметрами string, void.Так вот ему не нравится как я вызываю функцию Count с параметрами.Не может конвертировать тип.Как мне правильно вызвать функцию с параметрами?Подозреваю что надо использовать лямбда-функцию,но не уверен.
задан 25 окт 2018 в 16:38
KamaKama
414 бронзовых знака
3
У конструктора DxMenuItem
, всего две перегрузки с двумя параметрами:
DXMenuItem(string caption, DXMenuItemPriority priority)
DXMenuItem(string caption, EventHandler click)
Вероятнее всего имелась ввиду вторая перегрузка принимающая обработчик click.
В этом случае действительно можно передать lambda
new DxMenuItem(str, (s,e)=> Count(...))
ответ дан 25 окт 2018 в 17:09
Grundy♦Grundy
79k9 золотых знаков73 серебряных знака130 бронзовых знаков
1
Дело в ожидаемых типах параметров конструктора DXMenuItem
. Вряд ли тип второго параметра void
(.
Собственно у делегата DXMenuItem есть конструктор с параметрами
string, void.
Маловероятно также, что тип DXMenuItem
является делегатом. Похоже, в процитированной фразе Вы пытаетесь описать сигнатуру метода: параметр — string
, возвращаемое значение — void
.
ответ дан 25 окт 2018 в 17:00
2
See more:
public class CommandHandler { private DiscordSocketClient _client; private CommandService _service; public CommandHandler(DiscordSocketClient client) { _client = client; _service = new CommandService(); _service.AddModuleAsync(Assembly.GetEntryAssembly()); _client.MessageReceived += HandleCommandAsync; } private async Task HandleCommandAsync(SocketMessage s) { var msg = s as SocketUserMessage; if (msg == null) return; var context = new SocketCommandContext(_client, msg); int argPos = 0; if (msg.HasCharPrefix('!', ref argPos)) { var result = await _service.ExecuteAsync(context, argPos); if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) { await context.Channel.SendMessageAsync(result.ErrorReason); } } } }
What I have tried:
Nothing much I don’t know that much about C#
Solution 1
Start by looking at your CommandService class, and specifically at the AddModuleAsync method.
The chances are that it expects a Type, and you are passing an Assembly.
We can’t do that for you; we don’t have any access to your other code!
Solution 2
AddModulesAsync
With an «s»: Modules
See more:
public class CommandHandler { private DiscordSocketClient _client; private CommandService _service; public CommandHandler(DiscordSocketClient client) { _client = client; _service = new CommandService(); _service.AddModuleAsync(Assembly.GetEntryAssembly()); _client.MessageReceived += HandleCommandAsync; } private async Task HandleCommandAsync(SocketMessage s) { var msg = s as SocketUserMessage; if (msg == null) return; var context = new SocketCommandContext(_client, msg); int argPos = 0; if (msg.HasCharPrefix('!', ref argPos)) { var result = await _service.ExecuteAsync(context, argPos); if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) { await context.Channel.SendMessageAsync(result.ErrorReason); } } } }
What I have tried:
Nothing much I don’t know that much about C#
Solution 1
Start by looking at your CommandService class, and specifically at the AddModuleAsync method.
The chances are that it expects a Type, and you are passing an Assembly.
We can’t do that for you; we don’t have any access to your other code!
Solution 2
AddModulesAsync
With an «s»: Modules
Sibya 0 / 0 / 0 Регистрация: 18.03.2017 Сообщений: 85 |
||||
1 |
||||
28.04.2017, 17:54. Показов 7334. Ответов 4 Метки нет (Все метки)
Добрый вечер, не могу понять как исправить данные ошибки:
Код должен выполнять регистрацию новых пользователей и вносить их данные сразу в две таблицы. Будет еще супер, если подскажите, как добавлять в таблицу вместе с этими данными нынешнюю дату. Так же данные заносятся в две таблицы, но пользователь один. Между таблицами есть связь через Номер читателя. Как сделать автоматическое добавление в две таблице идентичного ключа?
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
28.04.2017, 17:54 |
4 |
Администратор 15248 / 12287 / 4904 Регистрация: 17.03.2014 Сообщений: 24,883 Записей в блоге: 1 |
|
28.04.2017, 17:59 |
2 |
Sibya, убери точку с запятой после if
1 |
Даценд 5858 / 4735 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
||||
28.04.2017, 18:05 |
3 |
|||
Sibya,
1 |
0 / 0 / 0 Регистрация: 18.03.2017 Сообщений: 85 |
|
29.04.2017, 13:46 [ТС] |
4 |
Все сделал и заработало. спасибо, но появляется ошибка во время регистрации в строке 9 появляется ошибка «Необработанное исключение типа «System.Data.SqlClient.SqlException» в System.Data.dll»
0 |
Даценд 5858 / 4735 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
||||
29.04.2017, 13:46 |
5 |
|||
Sibya,
О параметрах команды слышали?
1 |
Ошибку как исправить?
Вот такие ошибки:
Ошибка CS1503 Аргумент 1: не удается преобразовать из «string» в «char».
Ошибка CS1503 Аргумент 1: не удается преобразовать из «string» в «char».
Ошибка CS1503 Аргумент 2: не удается преобразовать из «string» в «char».
Ошибка CS1503 Аргумент 2: не удается преобразовать из «string» в «char».
using System; using System.IO; using System.Collections.Generic; namespace Grapher { class Program { static void Main(string[] args) { string[] data = File.ReadAllLines("массив.txt"); int length = data[0].Split(';').Length, i; Graph graph = new Graph(); for (i = 0; i < length; i++) { string[] str = data[i].Split(';'); var vertices = new Dictionary<char, int>(); for (int j = 0; j < length; j++) if (Convert.ToInt32(str[j]) != 0) vertices.Add(Char.Parse((j + 1).ToString()), Convert.ToInt32(str[j])); graph.add_vertex(Char.Parse((i + 1).ToString()), vertices); } string start = Console.ReadLine(); // Номер начального пункта string end = Console.ReadLine(); // Номер конечного пункта var result = graph.all_ways(start, end, "", 0); using (var sw = new StreamWriter("результат.txt")) { foreach (var item in result) sw.WriteLine(item); sw.WriteLine("Кратчайшее расстояние равно " + graph.shortest_path(start, end)); } Console.Write("Результат был сохранен в файле результат.txt"); Console.ReadLine(); } } } class Graph { Dictionary<char, Dictionary<char, int>> vertices = new Dictionary<char, Dictionary<char, int>>(); public void add_vertex(char name, Dictionary<char, int> edges) { vertices[name] = edges; } public List<string> all_ways(char current, char end, string path, int weight) { List<string> pathes = new List<string>(); if (path.IndexOf(current.ToString() + " ") != -1) return pathes; else if (path == "") path = current.ToString() + " = 0"; else { int index = path.IndexOf("="); string temp = path.Substring(0, index); string sum = path.Substring(index + 1); weight += Convert.ToInt32(sum); path = temp + "-> " + current.ToString() + " = " + weight.ToString(); } if (current == end) { pathes.Add(path); return pathes; } foreach (KeyValuePair<char, int> pair in vertices[current]) { List<string> result = all_ways(pair.Key, end, path, pair.Value); if (result.Count != 0) pathes.AddRange(result); } return pathes; } public int shortest_path(char start, char finish) { var previous = new Dictionary<char, char>(); var distances = new Dictionary<char, int>(); var nodes = new List<char>(); List<char> path = null; foreach (var vertex in vertices) { if (vertex.Key == start) { distances[vertex.Key] = 0; } else { distances[vertex.Key] = int.MaxValue; } nodes.Add(vertex.Key); } while (nodes.Count != 0) { nodes.Sort((x, y) => distances[x] - distances[y]); var smallest = nodes[0]; nodes.Remove(smallest); if (smallest == finish) { path = new List<char>(); while (previous.ContainsKey(smallest)) { path.Add(smallest); smallest = previous[smallest]; } break; } if (distances[smallest] == int.MaxValue) { break; } foreach (var neighbor in vertices[smallest]) { var alt = distances[smallest] + neighbor.Value; if (alt < distances[neighbor.Key]) { distances[neighbor.Key] = alt; previous[neighbor.Key] = smallest; } } } if (path.Count > 0) return distances[path[0]]; else return 0; } }
Прежде чем ответить, я снова и снова проверял свой код, а также около часа искал похожий ответ. Компилятор продолжает выдавать ошибку CS1503, я не совсем уверен, как это исправить. Это строки 36 и 37, и я прокомментировал строки с ошибками 36 и 37. Он предназначен для базы данных, которая должна искать номерной знак и выводить другие данные в таблицу.
public partial class Login : Form
{
string connectionString = @"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=J:Plate ReaderDBInfoDB.mdf;Integrated Security=True;Connect Timeout=30";
SqlDataReader mdr;
public Login()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
string selectQuery = "SELECT * From Plate WHERE Plate='" + txtPlate.Text;
SqlCommand command = new SqlCommand(selectQuery, sqlCon);
mdr = command.ExecuteReader();
if (mdr.Read())
{
labelName.Text = mdr.GetString("Name"); //Right here
labelWanted.Text = mdr.GetInt32("Bounty").ToString(); //and here
}
else
{
MessageBox.Show("No Data For This Plate");
}
}
}
}
3 ответа
Лучший ответ
Как объяснено в комментариях, GetString также GetInt32 требует параметр типа integer. Это целое число — позиция поля в списке выбора полей. Если вы не хотите использовать позицию, вы можете написать
labelName.Text = mdr.GetString(mdr.GetOrdinal("Name"));
И эту простую строку можно легко преобразовать в метод расширения, добавив метод в статический класс, чей код
public static class ReaderExtensions
{
public static string GetString(this SqlDataReader source, string fieldName)
{
return source.GetString(source.GetOrdinal(fieldName));
}
}
И это, наконец, позволяет писать
string labelText = mdr.GetString("Name");
Конечно, то же самое можно написать и для GetInt32, который принимает имя поля. Кстати, если я не ошибаюсь, версия MySql имеет эти перегрузки прямо в сборке
4
Steve
29 Дек 2018 в 19:33
GetInt32 ожидает параметр ‘int’.
Вы передаете в строке.
Вам необходимо отправить в порядковую позицию ваших столбцов.
Используйте это вместо:
mdr.GetInt32(mdr.GetOrdinal("Name"));
Возможно, вы захотите использовать микро ORM, например Dapper, чтобы упростить процесс.
1
KSK
29 Дек 2018 в 19:46
using System;
using UnityEngine;
using UnityEngine.InputSystem;
namespace platformer
{
public class HeroInput : MonoBehaviour
{
[SerializeField] private Hero _hero;
private HeroInputAction _inputActions;
private void Awake()
{
_inputActions = new HeroInputAction();
_inputActions.Hero.HorizontalMovement.performed += OnHorizontalMovement;
_inputActions.Hero.HorizontalMovement.canceled += OnHorizontalMovement;
_inputActions.Hero.SaySomething.performed += OnSaySomething;
}
private void OnEnable()
{
_inputActions.Enable();
}
private void OnHorizontalMovement(InputAction.CallbackContext context )
{
var direction = context.ReadValue<float>();
_hero.SetDirection(direction);
}
private void OnSaySomething(InputAction.CallbackContext context)
{
_hero.SaySomething();
}
}
}
Содержание
- Error cs1503 argument 1 cannot convert from system collections ienumerable to string
- Лучший отвечающий
- Вопрос
- Ответы
- Все ответы
- Error cs1503 argument 1 cannot convert from system collections ienumerable to string
- Answered by:
- Question
- Answers
- All replies
Error cs1503 argument 1 cannot convert from system collections ienumerable to string
Лучший отвечающий
Вопрос
I am trying to populate data from OpenWeatherMap using below code but getting this error:
Error CS1503 Argument 1: cannot convert from ‘Samana.WeatherInfo.List’ to ‘System.Collections.Generic.IEnumerable ‘
can anyone help please..
This is my code:
and the WeatherInfo is here:
Ответы
Maybe you should use this?
var result = JsonConvert.DeserializeObject ( data );
ObservableCollection trends = new ObservableCollection ( result.list );
Все ответы
Try add the following inside your WeatherInfo class:
Basically your problem is that, you’re just declaring a lot of class schema inside WeatherInfo without declaring any variable.
Источник
Error cs1503 argument 1 cannot convert from system collections ienumerable to string
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I am trying to populate data from OpenWeatherMap using below code but getting this error:
Error CS1503 Argument 1: cannot convert from ‘Samana.WeatherInfo.List’ to ‘System.Collections.Generic.IEnumerable ‘
can anyone help please..
This is my code:
and the WeatherInfo is here:
Answers
Maybe you should use this?
var result = JsonConvert.DeserializeObject ( data );
ObservableCollection trends = new ObservableCollection ( result.list );
Try add the following inside your WeatherInfo class:
Basically your problem is that, you’re just declaring a lot of class schema inside WeatherInfo without declaring any variable.
Источник