Ответы пользователя по тегу C#
  • Как отобразить подключение клиента к серверу?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    Console.WriteLine(((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString() + " connected");
    Ответ написан
    3 комментария
  • Если бы в интерфейсе можно было реализовывать желаемые методы без необходимости реализации в наследниках, то были бы тогда нужны абстрактные классы?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    А в Котлине есть возможность для некоторых методов интерфейса указать реализацию по-умолчанию :)

    kotlinlang.ru/docs/reference/interfaces.html
    Ответ написан
    Комментировать
  • Учить ASP.NET Core или Mvc для начала?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    Для начала лучше разобраться, что такое веб-сервер и зачем он нужен.
    И начать лучше с чего-нибудь простого, например HttpListener:
    https://msdn.microsoft.com/en-us/library/system.ne...
    (пример, который там приведен, объемом в пол-страницы — это готовый работающий веб-сервер)

    Потом вы сами легко сможете ответить на вопрос: нужен ли вам ASP.NET Core, MVC или еще что-либо — исходя из тех практических задач, которые перед вами будут возникать.
    Ответ написан
    Комментировать
  • Почему MouseHover и MouseLeave при событии, с параметрами Width и Height срабатывают не правильно?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    Пара взаимосвязанных событий — это MouseEnter и MouseLeave.
    MouseHover тут не нужен.
    Ответ написан
    2 комментария
  • Как правильно называть следующий синтаксис?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    Если уж вы добрались до таких сложных вопросов, то пора и книжки читать соответствующие:

    C# Language Specification:
    https://www.microsoft.com/en-us/download/details.a...

    В частности, по обозначенному вами вопросу там написано вот что:
    1.6.1 Members
    The members of a class are either static members or instance members. Static members belong to classes, and instance members belong to objects (instances of classes).


    1.6.5 Fields
    A field is a variable that is associated with a class or with an instance of a class.
    A field declared with the static modifier defines a static field. A static field identifies exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field.
    A field declared without the static modifier defines an instance field. Every instance of a class contains a separate copy of all the instance fields of that class.


    1.6.6 Methods
    A method is a member that implements a computation or action that can be performed by an object or class. Static methods are accessed through the class. Instance methods are accessed through instances of the class.


    1.6.6.3 Static and instance methods
    A method declared with a static modifier is a static method. A static method does not operate on a specific instance and can only directly access static members.
    A method declared without a static modifier is an instance method. An instance method operates on a specific instance and can access both static and instance members. The instance on which an instance method was invoked can be explicitly accessed as this. It is an error to refer to this in a static method.
    The following Entity class has both static and instance members.
    class Entity
    {
    	static int nextSerialNo;
    	int serialNo;
    	public Entity() {
    		serialNo = nextSerialNo++;
    	}
    	public int GetSerialNo() {
    		return serialNo;
    	}
    	public static int GetNextSerialNo() {
    		return nextSerialNo;
    	}
    	public static void SetNextSerialNo(int value) {
    		nextSerialNo = value;
    	}
    }

    Each Entity instance contains a serial number (and presumably some other information that is not shown here). The Entity constructor (which is like an instance method) initializes the new instance with the next available serial number. Because the constructor is an instance member, it is permitted to access both the serialNo instance field and the nextSerialNo static field.
    The GetNextSerialNo and SetNextSerialNo static methods can access the nextSerialNo static field, but it would be an error for them to directly access the serialNo instance field.
    The following example shows the use of the Entity class.
    using System;
    class Test
    {
    	static void Main() {
    		Entity.SetNextSerialNo(1000);
    		Entity e1 = new Entity();
    		Entity e2 = new Entity();
    		Console.WriteLine(e1.GetSerialNo());				// Outputs "1000"
    		Console.WriteLine(e2.GetSerialNo());				// Outputs "1001"
    		Console.WriteLine(Entity.GetNextSerialNo());		// Outputs "1002"
    	}
    }

    Note that the SetNextSerialNo and GetNextSerialNo static methods are invoked on the class whereas the GetSerialNo instance method is invoked on instances of the class.
    Ответ написан
    3 комментария
  • Как создать WPF окно в Dll?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    Все просто. Кнопка "добавить окно" отсутствует, но никаких запретов на окна в dll нет.

    На вскидку пара способов, как обойтись без кнопки:

    1. Создаете UserControl, переименовываете его в Window.

    2. Копируете пару файлов xaml и xaml.cs в папку проекта. В обозревателе решений жмем "Показать все файлы" - показываются те, которые не включены в проект, выбираем их, включаем в проект.
    Ответ написан
    Комментировать
  • Почему TLSharp не возвращает значения?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    Async void это запустили фоновый поток и забыли о нем. Соответственно, основной поток приложения (откуда вызывается Start) завершается мгновенно, не дожидаясь завершения работы Start.
    А чтобы дождаться, имеет смысл объявить Start как async Task, а при вызове из Main (или любого другого места, где нет возможности написать await Start()) - использовать синхронный вызов, т.е. Start().Wait()
    Ответ написан
    Комментировать
  • Как таблицу из docx без боли перенести в DataSet?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    Без гемора вряд ли.
    Однако, разбор docx - не такая уж и сложная задача. Распаковываем zip-архив (т.е. docx) вызовом 7-zip-а, берем оттуда xml и разбираем его с помощью XDocument, либо XmlDocument - что больше нравится.
    Ответ написан
    Комментировать
  • Инструмент в wpf для быстрого вывода большой текстовой информации?

    AlexanderYudakov
    @AlexanderYudakov
    C#, 1С, Android, TypeScript
    От скуки нарисовал более простое решение - custom panel, которая отображает сетку с ячейками фиксированного размера. Border-ы, Background-ы ячеек - на ваше усмотрение в методах CreateCell и BindCell.

    Пробовал 1 млн х 1 млн ячеек - никаких тормозов. Отображается только то, что видно на экране.

    59e9ec8d02f32162485723.png
    <Window x:Class="GridTest.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:GridTest"
            Title="Square Grid Test" Height="350" Width="525">
        <ScrollViewer CanContentScroll="True" 
                    HorizontalScrollBarVisibility="Visible"
                    VerticalScrollBarVisibility="Visible">
            <local:SquareGrid x:Name="Grid">
            </local:SquareGrid>
        </ScrollViewer>
    </Window>


    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    
    namespace GridTest
    {
        public partial class MainWindow : Window, SquareGrid.ICellGenerator
        {
            public MainWindow()
            {
                InitializeComponent();
    
                Grid.RowCount = 1000;
                Grid.ColumnCount = 1000;
                Grid.CellWidth = 36;
                Grid.CellGenerator = this;
            }
    
            public UIElement CreateCell()
            {
                return new Border
                {
                    Child = new TextBlock
                    {
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                        FontSize = 10
                    },
                    BorderBrush = Brushes.LightGray,
                    BorderThickness = new Thickness(0, 0, 1, 1)
                };
            }
    
            public void BindCell(UIElement view, int x, int y)
            {
                var border = (Border)view;
                var textBlock = (TextBlock)border.Child;
                textBlock.Text = "" + x + ":" + y;
            }
        }
    }


    public sealed class SquareGrid : Panel, IScrollInfo
    {
        // Подробности сюда не влезли,
        // см. SquareGrid.cs
    }

    SquareGrid.cs

    Проект целиком: SquareGrid.zip
    Ответ написан
    2 комментария