Ошибка cs0121 неоднозначный вызов следующих методов или свойств

  1. Create a new ASP.NET MVC Web
    Application
  2. Create an ASP.NET App_Code
    Folder
  3. Inside the new
    folder, create a class with an
    Extension Method. For example:

    static public class BugMVCExtension
    {
        public static int ToInt(this string str)
        {
            return Convert.ToInt32(str);
        }
    }
    
  4. Choose a View and try to use this new Extension Method

You will get this Exception:

CS0121: The call is ambiguous between the following methods or properties:
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' and
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*'

Anyone here has more information about it?
Is it wrong to create an App_code in an ASP.NET MVC(?) Web Applications?

MVC projects created in Visual Studio use Web application project model by default. App_Code is mostly used by Web site model. I suggest reading about differences between them (another question covers this and it’s also covered extensively on MSDN). If you add a source file to App_Code in a Web application project, Visual Studio will compile it to a DLL (since it’s included in the project) and puts it in /bin. At run time, the ASP.NET compiler sees App_Code and tries to compile the source in a different assembly. As a consequence, two separate classes with identical names will exist in two different assemblies and when the ASP.NET parser tries to compile the .aspx file, it’ll fail to choose one.

Update:

Are those two (extension method and the class you’re instantiating) in a single .cs file? Otherwise, probably, the class you’re instantiating is in a source file with Build Action (right click on file, click properties) set to Content which tells Visual Studio to skip it in the build process (in that case, you won’t be able to reference it in other .cs files that are outside App_Code but you’ll be able to use it in the view since it’ll only come to life at run time.) If the build action is Compile, you’ll get an error. The issue is definitely not specific to extension methods. Visual Studio seems to be smart enough to set it to Content by default for source files added to App_Code.

Community's user avatar

answered Aug 15, 2009 at 19:32

Mehrdad Afshari's user avatar

Mehrdad AfshariMehrdad Afshari

413k91 gold badges851 silver badges789 bronze badges

8

Do not use the app_code folder.

Use any other folder name. IE. appCode or ApplicationsCode.

The name in the folder implies some compilation at runtime that leads to have duplicated code.

1

I solved the problem by placing the .cs file outside the App_Code folder, in the root of the Web Application.

I solved by placing in the file of extension of the full namespace of the folder.

namespace Helpers
{

namespace xxx.yyy.zzz.Helpers
{

This is the craziest what I’ve seen since a Fody plugin ruined my assembly by emitting invalid code and control flow varied random at runtime… No Fody this time.

Facts:

  • The whole story is within one project.
  • The GetMessage extension method is there since weeks…
  • The issue is started since 2 hours, and I can not figure out what it is.
  • There is only one GetMessage extension method.
  • The error message (see the pic) lists two identical method specification

    Error CS0121 The call is ambiguous between the following methods or properties: 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' and 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' ComiCalc.Data D:2014Develop.vsonlineComiCalcsrcComiCalc.DataServicesUserService.cs 61

  • If I change both the call, both the method definition (only 2 edits in 2 places) to GetMessage2, then I got exactly the same error message just referring to the GetMessage2.

  • Using VS 2015

Any ideas?

enter image description here

and here is the single one method:

namespace ComiCalc.Data
{

    using System;
    using System.Data.Entity.Validation;
    using PluralTouch.DataAccess;
    // TODO: Move to PluralTouch
    public static class ExceptionExtensions
    {
        public static string GetMessage2(this Exception exception)
        {

            var message = exception.Message;
            if (exception is DbEntityValidationException)
            {
                message = ((DbEntityValidationException) exception).DbEntityValidationResultToString();
            }
            return message;
        }
    }
}

enter image description here

asked Jul 30, 2015 at 16:24

g.pickardou's user avatar

g.pickardoug.pickardou

31.7k35 gold badges122 silver badges261 bronze badges

6

Make sure you don’t reference the output binary in your project references (i.e., the project references itself). This has happened to me in the past with Resharper (the addition of the output binary to the project references), so the extension method is both in the source and in the binary reference.

answered Jul 30, 2015 at 16:29

Jcl's user avatar

JclJcl

27.5k5 gold badges60 silver badges90 bronze badges

2

Delete bin folder > open project > build solution.

answered Apr 15, 2018 at 13:08

serdar's user avatar

serdarserdar

4541 gold badge8 silver badges26 bronze badges

Got the same error because my project referenced to a dll, and at the same time had a transitive dependency to the same dll but at different file path.

Spotted it using extra logging during the build (Tools -> Options -> Build and Run ->output verbosity to Detailed or Diagnostic) by searching for dependency dll name: in Task «Csc» there were two occurrences of /reference with the dll

Fix was to point references to the same dll path

answered Feb 27, 2019 at 13:00

Renat's user avatar

RenatRenat

7,5702 gold badges20 silver badges34 bronze badges

In my case, Resharper had created a new file named Annotations1.cs file. I just deleted it and the problem solved. Maybe you need delete debug / release / obj and clean / rebuild solution.

enter image description here

answered Feb 24, 2021 at 19:52

Ayub's user avatar

AyubAyub

2,33527 silver badges29 bronze badges

I created a new project and moved all files except ‘bin’, ‘references’, ‘obj’ and boom. It works like charm..

answered Apr 29, 2017 at 15:08

Erdogan's user avatar

ErdoganErdogan

95212 silver badges25 bronze badges

I had two exact classes created by a DB tool, because was executed 2 times with different parameters. I search by the class name and remove the newer, after that everything goes OK.

answered Oct 6, 2020 at 5:07

jaimenino's user avatar

In my case I had the «publish» folder within my project folder. Removing the «publish» folder solved it for me.

answered Oct 21, 2020 at 8:51

LiliumCandidum's user avatar

In my case, I hit the same problem [impossible resolution conflicts between a single method and itself] because I used C# 8.0 and its shiny new features to build three projects that depend upon each other, transitively, like this:

  • Project C depends on project B.
  • Project B depends on project A.
  • Project C calls APIs from types in project B that inherit types from project A. Some of those APIs have nullable reference type parameters.

Also, I had nullability checking enabled only for project A, and completely disabled for projects B and C.

The fix for me was to enable nullable annotations in project B (I did this without also enabling warnings).

I speculate that this fixes the problem by ensuring there weren’t two completely different compiler modes (nullable annotated on/off) reprocessing the same interface definition, while building two projects (A and B), and then up putting conflicting nullability annotations on their respective outputs.

answered Sep 2, 2021 at 22:48

Tim Lovell-Smith's user avatar

Tim Lovell-SmithTim Lovell-Smith

15k14 gold badges74 silver badges93 bronze badges

I had the same issue while migrating from .NET3.1 to .NET6.0. I got my issue fixed by updating the reference package «System.Interactive» to the latest version (6.0.1 in my case) in csproj file.

answered Feb 2 at 6:23

Shaheera Fatima Khan's user avatar

In my case I just have add «path» to the code!!! hope that helps error CS0121

answered Feb 27 at 20:32

Neftaly Perez's user avatar

  1. Create a new ASP.NET MVC Web
    Application
  2. Create an ASP.NET App_Code
    Folder
  3. Inside the new
    folder, create a class with an
    Extension Method. For example:

    static public class BugMVCExtension
    {
        public static int ToInt(this string str)
        {
            return Convert.ToInt32(str);
        }
    }
    
  4. Choose a View and try to use this new Extension Method

You will get this Exception:

CS0121: The call is ambiguous between the following methods or properties:
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' and
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*'

Anyone here has more information about it?
Is it wrong to create an App_code in an ASP.NET MVC(?) Web Applications?

MVC projects created in Visual Studio use Web application project model by default. App_Code is mostly used by Web site model. I suggest reading about differences between them (another question covers this and it’s also covered extensively on MSDN). If you add a source file to App_Code in a Web application project, Visual Studio will compile it to a DLL (since it’s included in the project) and puts it in /bin. At run time, the ASP.NET compiler sees App_Code and tries to compile the source in a different assembly. As a consequence, two separate classes with identical names will exist in two different assemblies and when the ASP.NET parser tries to compile the .aspx file, it’ll fail to choose one.

Update:

Are those two (extension method and the class you’re instantiating) in a single .cs file? Otherwise, probably, the class you’re instantiating is in a source file with Build Action (right click on file, click properties) set to Content which tells Visual Studio to skip it in the build process (in that case, you won’t be able to reference it in other .cs files that are outside App_Code but you’ll be able to use it in the view since it’ll only come to life at run time.) If the build action is Compile, you’ll get an error. The issue is definitely not specific to extension methods. Visual Studio seems to be smart enough to set it to Content by default for source files added to App_Code.

Community's user avatar

answered Aug 15, 2009 at 19:32

mmx's user avatar

8

Do not use the app_code folder.

Use any other folder name. IE. appCode or ApplicationsCode.

The name in the folder implies some compilation at runtime that leads to have duplicated code.

1

I solved the problem by placing the .cs file outside the App_Code folder, in the root of the Web Application.

I solved by placing in the file of extension of the full namespace of the folder.

namespace Helpers
{

namespace xxx.yyy.zzz.Helpers
{

  1. Create a new ASP.NET MVC Web
    Application
  2. Create an ASP.NET App_Code
    Folder
  3. Inside the new
    folder, create a class with an
    Extension Method. For example:

    static public class BugMVCExtension
    {
        public static int ToInt(this string str)
        {
            return Convert.ToInt32(str);
        }
    }
    
  4. Choose a View and try to use this new Extension Method

You will get this Exception:

CS0121: The call is ambiguous between the following methods or properties:
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' and
'*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*'

Anyone here has more information about it?
Is it wrong to create an App_code in an ASP.NET MVC(?) Web Applications?

MVC projects created in Visual Studio use Web application project model by default. App_Code is mostly used by Web site model. I suggest reading about differences between them (another question covers this and it’s also covered extensively on MSDN). If you add a source file to App_Code in a Web application project, Visual Studio will compile it to a DLL (since it’s included in the project) and puts it in /bin. At run time, the ASP.NET compiler sees App_Code and tries to compile the source in a different assembly. As a consequence, two separate classes with identical names will exist in two different assemblies and when the ASP.NET parser tries to compile the .aspx file, it’ll fail to choose one.

Update:

Are those two (extension method and the class you’re instantiating) in a single .cs file? Otherwise, probably, the class you’re instantiating is in a source file with Build Action (right click on file, click properties) set to Content which tells Visual Studio to skip it in the build process (in that case, you won’t be able to reference it in other .cs files that are outside App_Code but you’ll be able to use it in the view since it’ll only come to life at run time.) If the build action is Compile, you’ll get an error. The issue is definitely not specific to extension methods. Visual Studio seems to be smart enough to set it to Content by default for source files added to App_Code.

Community's user avatar

answered Aug 15, 2009 at 19:32

mmx's user avatar

8

Do not use the app_code folder.

Use any other folder name. IE. appCode or ApplicationsCode.

The name in the folder implies some compilation at runtime that leads to have duplicated code.

1

I solved the problem by placing the .cs file outside the App_Code folder, in the root of the Web Application.

I solved by placing in the file of extension of the full namespace of the folder.

namespace Helpers
{

namespace xxx.yyy.zzz.Helpers
{

This is the craziest what I’ve seen since a Fody plugin ruined my assembly by emitting invalid code and control flow varied random at runtime… No Fody this time.

Facts:

  • The whole story is within one project.
  • The GetMessage extension method is there since weeks…
  • The issue is started since 2 hours, and I can not figure out what it is.
  • There is only one GetMessage extension method.
  • The error message (see the pic) lists two identical method specification

    Error CS0121 The call is ambiguous between the following methods or properties: 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' and 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' ComiCalc.Data D:2014Develop.vsonlineComiCalcsrcComiCalc.DataServicesUserService.cs 61

  • If I change both the call, both the method definition (only 2 edits in 2 places) to GetMessage2, then I got exactly the same error message just referring to the GetMessage2.

  • Using VS 2015

Any ideas?

enter image description here

and here is the single one method:

namespace ComiCalc.Data
{

    using System;
    using System.Data.Entity.Validation;
    using PluralTouch.DataAccess;
    // TODO: Move to PluralTouch
    public static class ExceptionExtensions
    {
        public static string GetMessage2(this Exception exception)
        {

            var message = exception.Message;
            if (exception is DbEntityValidationException)
            {
                message = ((DbEntityValidationException) exception).DbEntityValidationResultToString();
            }
            return message;
        }
    }
}

enter image description here

asked Jul 30, 2015 at 16:24

g.pickardou's user avatar

g.pickardoug.pickardou

30.5k35 gold badges114 silver badges248 bronze badges

6

Make sure you don’t reference the output binary in your project references (i.e., the project references itself). This has happened to me in the past with Resharper (the addition of the output binary to the project references), so the extension method is both in the source and in the binary reference.

answered Jul 30, 2015 at 16:29

Jcl's user avatar

JclJcl

27.2k5 gold badges60 silver badges87 bronze badges

2

Delete bin folder > open project > build solution.

answered Apr 15, 2018 at 13:08

serdar's user avatar

serdarserdar

4451 gold badge8 silver badges26 bronze badges

Got the same error because my project referenced to a dll, and at the same time had a transitive dependency to the same dll but at different file path.

Spotted it using extra logging during the build (Tools -> Options -> Build and Run ->output verbosity to Detailed or Diagnostic) by searching for dependency dll name: in Task «Csc» there were two occurrences of /reference with the dll

Fix was to point references to the same dll path

answered Feb 27, 2019 at 13:00

Renat's user avatar

RenatRenat

7,2202 gold badges20 silver badges33 bronze badges

In my case, Resharper had created a new file named Annotations1.cs file. I just deleted it and the problem solved. Maybe you need delete debug / release / obj and clean / rebuild solution.

enter image description here

answered Feb 24, 2021 at 19:52

Ayub's user avatar

AyubAyub

2,24526 silver badges29 bronze badges

I created a new project and moved all files except ‘bin’, ‘references’, ‘obj’ and boom. It works like charm..

answered Apr 29, 2017 at 15:08

Erdogan's user avatar

ErdoganErdogan

95212 silver badges25 bronze badges

I had two exact classes created by a DB tool, because was executed 2 times with different parameters. I search by the class name and remove the newer, after that everything goes OK.

answered Oct 6, 2020 at 5:07

jaimenino's user avatar

In my case I had the «publish» folder within my project folder. Removing the «publish» folder solved it for me.

answered Oct 21, 2020 at 8:51

LiliumCandidum's user avatar

In my case, I hit the same problem [impossible resolution conflicts between a single method and itself] because I used C# 8.0 and its shiny new features to build three projects that depend upon each other, transitively, like this:

  • Project C depends on project B.
  • Project B depends on project A.
  • Project C calls APIs from types in project B that inherit types from project A. Some of those APIs have nullable reference type parameters.

Also, I had nullability checking enabled only for project A, and completely disabled for projects B and C.

The fix for me was to enable nullable annotations in project B (I did this without also enabling warnings).

I speculate that this fixes the problem by ensuring there weren’t two completely different compiler modes (nullable annotated on/off) reprocessing the same interface definition, while building two projects (A and B), and then up putting conflicting nullability annotations on their respective outputs.

answered Sep 2, 2021 at 22:48

Tim Lovell-Smith's user avatar

Tim Lovell-SmithTim Lovell-Smith

14.7k14 gold badges73 silver badges92 bronze badges

C# Compiler Error

CS0121 – The call is ambiguous between the following methods or properties: ‘method1’ and ‘method2′

Reason for the Error

You will receive this error when you usually call one of the overloaded method and the C# compiler is not able to call it because of the conflict with the parameters caused by implicit conversion.

For example, let’s have a look at the below C# code snippet.

namespace DeveloperPublishNamespace
{
    public class DeveloperPublish
    {
        public static void Method1(int input1,double input2)
        { 

        }
        public static void Method1(double input1,int input2)
        {

        }
        
        public static void Main()
        {
            Method1(5,5);        
		}
    }
}

This contains 2 overloaded functions with different parameter type. When this function is called with the parameter 5,5, it results with the below error.

Error CS0121 The call is ambiguous between the following methods or properties: ‘DeveloperPublish.Method1(int, double)’ and ‘DeveloperPublish.Method1(double, int)’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active

C# compiler was not able to identify which overloaded method to call because of the values that is passed which results in the implicit conversion.

Solution

There are plenty of ways in which you can avoid this error. You can either specify the parameter type with the explicit conversion so that the implicit conversion doesn’t take place or possibly use a named arguments.

Ошибка при компиляции — Неоднозначный вызов следующих методов или свойств Task.Run

Ошибка при компиляции — Неоднозначный вызов следующих методов или свойств Task.Run

Статус темы:

Закрыта.
  1. Добрый день! Скачал с гитхаба последнюю версию проекта. При компиляции проекта выдаются ошибки:

    Ошибка    CS0121    Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)»    OsEngine    e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs    196    Активный

    Серьезность    Код    Описание    Проект    Файл    Строка    Состояние подавления
    Ошибка    CS0121    Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)»    OsEngine    e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs    325    Активный

    Скачать error.png 60 Кб

    arkadiy_vl

  2. Цитата: arkadiy_vl

    Добрый день! Скачал с гитхаба последнюю версию проекта. При компиляции проекта выдаются ошибки:

    Ошибка    CS0121    Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)»    OsEngine    e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs    196    Активный

    Серьезность    Код    Описание    Проект    Файл    Строка    Состояние подавления
    Ошибка    CS0121    Неоднозначный вызов следующих методов или свойств: ‘Task.Run(Action, CancellationToken)» и «Task.Run(Func<Task>, CancellationToken)»    OsEngine    e:SITESOsEngine-master-2020-04-11projectOsEngineMarketServersTransaqTransaqServer.cs    325    Активный

    закомментируйте пока. Пройдёт. Поправим 

    Алексей Ван

  3. фикс на гитХабе.

    Только вот у меня эта ошибка не всплывала. Синтаксис поменял. Отпишитесь, отпустило или нет.

    Алексей Ван

  4. Цитата: Алексей Ван
    Только вот у меня эта ошибка не всплывала. Синтаксис поменял. Отпишитесь, отпустило или нет.

    Добрый день, Алексей! Скачал последнюю версию с гитхаба. Проект скомпилировался без ошибок. Проблема с неоднозначным вызовом методов ушла. Спасибо!

    arkadiy_vl

Статус темы:

Закрыта..

Проекты MVC, созданные в Visual Studio, используют модель проекта веб-приложения по умолчанию. App_Code в основном используется моделью веб-сайта. Я предлагаю прочитать о различиях между ними (другой вопрос охватывает этот вопрос, а также широко распространяется на MSDN). Если вы добавляете исходный файл в App_Code в проект веб-приложения, Visual Studio будет компилировать его в DLL (так как он включен в проект) и помещает его в /bin. Во время выполнения компилятор ASP.NET видит App_Code и пытается скомпилировать источник в другой сборке. Как следствие, два разных класса с одинаковыми именами будут существовать в двух разных сборках, и когда парсер ASP.NET попытается скомпилировать файл .aspx, он не сможет выбрать его.

Обновление:

Являются ли эти два (метод расширения и класс, который вы создаете) в одном файле .cs? В противном случае, возможно, создаваемый вами класс находится в исходном файле с Строить действие (щелкните правой кнопкой мыши по файлу, щелкните свойства), установленным в Контент, который сообщает Visual Studio пропустить он в процессе сборки (в этом случае вы не сможете ссылаться на него в других файлах .cs, которые находятся за пределами App_Code, но вы сможете использовать его в представлении, поскольку он только оживет во время выполнения.) Если действие сборки Компилировать, вы получите сообщение об ошибке. Эта проблема определенно не специфична для методов расширения. Visual Studio кажется достаточно умным, чтобы установить его в Content по умолчанию для исходных файлов, добавленных в App_Code.

#c# #implicit-conversion #ambiguous-call

Вопрос:

У меня есть несколько классов C#, MyChar, Myint, myDouble, которые переносят символы char, int и double. У каждого есть неявный оператор преобразования из обернутого типа в определенный пользователем. У меня также есть набор перегруженных функций, toString(MyChar), toString(myInt), toString(myDouble).

Я хочу вызвать toString(MyChar), передав буквальное значение символа, например «A». Но компиляция завершается неудачно с CS0121, «Вызов неоднозначен между следующими методами или свойствами:» toString(MyChar)» и «toString(myInt)»». И у меня возникает аналогичная проблема, если я передаю значение int.

     public class MyChar
    {
        private MyChar(char val) => Value = val;
        public static implicit operator MyChar(char val) => new MyChar(val);
        public char Value { get; }
    }
    public class MyInt
    {
        private MyInt(int val) => Value = val;
        public static implicit operator MyInt(int val) => new MyInt(val);
        public int Value { get; }
    }
    public class MyDouble
    {
        private MyDouble(double val) => Value = val;
        public static implicit operator MyDouble(double val) => new MyDouble(val);
        public double Value { get; }
    }

    public class ConversionTests
    {
        public void DoIt()
        {
            Console.WriteLine(ToString('A')); // CS0121
            Console.WriteLine(ToString(1)); // CS0121
        }

        private static string ToString(MyChar c) => $"{c.Value}";
        private static string ToString(MyInt i) => $"{i.Value}";
        private static string ToString(MyDouble d) => $"{d.Value}";
    }
 

Я обнаружил, что могу заставить компилятор правильно принимать значение int, добавив неявное преобразование из myInt в myDouble

     public class MyDouble
    {
        private MyDouble(double val) => Value = val;
        public static implicit operator MyDouble(double val) => new MyDouble(val);
        public static implicit operator MyDouble(MyInt val) => new MyDouble(val.Value);
        public double Value { get; }
    }
...
        public void DoIt()
        {
            Console.WriteLine(ToString('A')); // CS0121
            Console.WriteLine(ToString(1)); // now compiles :-)
        }
 

Я предполагаю, что это работает, потому что механизм разрешения теперь считает, что преобразование в myDouble теперь выполняется по маршруту 1 -> myInt ->> myDouble, и это не может произойти неявно, поскольку для этого требуется два пользовательских преобразования. В том же духе я могу ToString('A') решить проблему правильно, добавив еще два неявных преобразования: MyChar в myDouble и MyChar в myInt.

Это нормально, так как оно отражает неявные преобразования, которые происходят между символами char, int и double. Но может ли кто-нибудь объяснить мне, почему исходный код, опубликованный выше, не будет компилироваться без дополнительных преобразований так, как мог бы понять простой мозг, подобный моему?

Комментарии:

1.A Char может быть неявно приведено к an Int . An int может быть неявно приведено к double . Учитывая неявные приведения к My типам, это означает, что ToString('A') это может быть обработано обоими ToString методами. Вы можете удалить все ToString() методы, кроме ToString(MyInt) , и код все равно будет работать

2. Что ты пытаешься сделать? Вы пробуете что-то или это упрощенный случай реальной проблемы?

3. @PanagiotisKanavos Это самое простое сокращение проблемы, которую я нашел в своем коде. Я хочу представить полный API, поэтому у меня нет роскоши удалять методы. Я хочу использовать перегруженное имя, так как в сознании пользователя операция-это одно и то же, независимо от типа, на котором она выполняется. Чего я не понимаю, так это почему символ преобразования -> MyChar не выбран в качестве однозначного преобразования, поскольку он ближе, чем символ ->> int ->>> myInt.

4. опишите реальную проблему в самом вопросе. Ни одно из преобразований не находится ближе, чем другое. Все они требуют неявных приведений, поэтому ни одно из них не ближе другого. Для этих примеров существует несколько методов, которые могут быть вызваны после неявных приведений.

5. as in the user's mind the operation is the same thing, irrespective of the type its operating on. почему бы тогда не использовать общий метод? Приведите пример реальной проблемы. Вы можете использовать общий интерфейс для всех типов, использовать общие методы или использовать какой-либо другой трюк

Ответ №1:

A char может быть неявно приведено к an int . An int может быть неявно приведено к double . Учитывая неявные приведения к My типам, это означает, что ToString('A') это может быть обработано обоими ToString методами.

Вы можете удалить все ToString() методы, кроме ToString(MyInt) , и код все равно будет работать:

     public class ConversionTests
    {
        public void DoIt()
        {
            Console.WriteLine(ToString('A')); 
            Console.WriteLine(ToString(1));
        }

        private static string ToString(MyInt i) => $"{i.Value}";
    }
 

Это напечатало бы :

 65
1
 

У меня проблема —

System.Net.Http.HttpClientExtensions.PostAsJsonAsync (System.Net.Http.HttpClient, string, T, System.Threading.CancellationToken) и System.Net.Http.Json

private async Task Add()
{
    using (var msg = await Http.PostAsJsonAsync<Feedback>("/api/feedbacks", newcust, System.Threading.CancellationToken.None))
    {
        if (msg.IsSuccessStatusCode)
        {
            custs.Add(await msg.Content.ReadFromJsonAsync<Feedback>());
            newcust.title = newcust.rating = newcust.comment = null;
        }
    }

    if (ValidReCAPTCHA)
    {
        var response = await reCAPTCHAComponent.GetResponseAsync();
        try
        {
            ServerVerificatiing = true;
            StateHasChanged();
            await Http.PostAsJsonAsync("/api/sample", new SampleAPIArgs { reCAPTCHAResponse = response });
            Navigation.NavigateTo("/valid");
        }
        catch (HttpRequestException e)
        {
            await JS.InvokeAsync<object>("alert", e.Message);
            ServerVerificatiing = false;
            StateHasChanged();
        }
    }
}

Скриншот Изображение

2 ответа

Лучший ответ

Использовать

System.Net.Http.Json.HttpClientJsonExtensions.PostAsJsonAsync

Вместо того

System.Net.Http.HttpClientExtensions.PostAsJsonAsync

Вам могут понадобиться некоторые из них, используя:

using System.Net.Http.Json;
using System.Net.Http;
using System.Text.Json;
using System.Text;
using System.Text.Json.Serialization;

Удалите любые ссылки на System.Net.Http.HttpClientExtensions
Ниже приведен код для установки System.Net.Http.Json, если он не установлен

Install-Package System.Net.Http.Json -Version 5.0.0


2

enet
5 Мар 2021 в 11:05

Метод Http.PostAsJsonAsync находится в двух пространствах имен — посмотрите, что на самом деле говорится в сообщении об ошибке.

Вы должны уточнять имя, чтобы компилятор знал, какое из них вы хотите использовать. В противном случае вы должны удалить один из конфликтующих using.

Как сказали PMF и Klaus в своих комментариях — пожалуйста, публикуйте код, а не скриншоты.


0

Claus H
5 Мар 2021 в 10:39

C# Compiler Error

CS0121 – The call is ambiguous between the following methods or properties: ‘method1’ and ‘method2′

Reason for the Error

You will receive this error when you usually call one of the overloaded method and the C# compiler is not able to call it because of the conflict with the parameters caused by implicit conversion.

For example, let’s have a look at the below C# code snippet.

namespace DeveloperPublishNamespace
{
    public class DeveloperPublish
    {
        public static void Method1(int input1,double input2)
        { 

        }
        public static void Method1(double input1,int input2)
        {

        }
        
        public static void Main()
        {
            Method1(5,5);        
		}
    }
}

This contains 2 overloaded functions with different parameter type. When this function is called with the parameter 5,5, it results with the below error.

Error CS0121 The call is ambiguous between the following methods or properties: ‘DeveloperPublish.Method1(int, double)’ and ‘DeveloperPublish.Method1(double, int)’ ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active

C# compiler was not able to identify which overloaded method to call because of the values that is passed which results in the implicit conversion.

Solution

There are plenty of ways in which you can avoid this error. You can either specify the parameter type with the explicit conversion so that the implicit conversion doesn’t take place or possibly use a named arguments.

kservice

0 / 0 / 0

Регистрация: 05.03.2016

Сообщений: 62

1

15.08.2022, 14:34. Показов 1289. Ответов 12

Метки forms, msdn, програмированние (Все метки)


Студворк — интернет-сервис помощи студентам

При использовании примера кода из MSDN возникло множество ошибок. В VS 2022 cоздал проект Windows Forms (Microsoft) C# и вставил код в Form1.cs

Ошибки:
CS0111 Тип «Program» уже определяет член «Main» с такими же типами параметров.
CS0102 Тип «Form1» уже содержит определение для «components».
CS0111 Тип «Form1» уже определяет член «InitializeComponent» с такими же типами параметров
CS0111 Тип «Form1» уже определяет член «Dispose» с такими же типами параметров.
CS0101 Пространство имен «ToolStripDropDownItemCS» уже содержит определение для «Program».
CS0260 Отсутствует модификатор partial в объявлении типа «Form1»; существует другое разделяемое объявление этого типа.
CS0121 Неоднозначный вызов следующих методов или свойств: «Form1.InitializeComponent()» и «Form1.InitializeComponent()»

и 7 ошибок в разных строках
CS0229 Неоднозначность между «Form1.components» и «Form1.components»

Код из Form1.cs и Form1.Designer.cs прилагаю
Код из Form1.cs

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
 
namespace ToolStripDropDownItemCS
{
    public class Form1 : Form
    {
        private ToolStrip toolStrip1;
        private StatusStrip statusStrip1;
        private ToolStripStatusLabel toolStripStatusLabel1;
        private ContextMenuStrip contextMenuStrip1;
        private ToolStripMenuItem menuItem1ToolStripMenuItem;
        private ToolStripMenuItem menuItem2ToolStripMenuItem;
        private ToolStripMenuItem subItemToolStripMenuItem;
        private ToolStripMenuItem subItem2ToolStripMenuItem;
        private Button showButton;
        private Button hideButton;
        private System.ComponentModel.IContainer components = null;
 
        public Form1()
        {
            InitializeComponent();
            this.InitializeToolStripDropDownItems();
        }
 
        // This utility method creates and initializes three 
        // ToolStripDropDownItem controls and adds them 
        // to the form's ToolStrip control.
        private void InitializeToolStripDropDownItems()
        {
            ToolStripDropDownButton b = new ToolStripDropDownButton("DropDownButton");
            b.DropDown = this.contextMenuStrip1;
            b.DropDownClosed += new EventHandler(toolStripDropDownItem_DropDownClosed);
            b.DropDownItemClicked += new ToolStripItemClickedEventHandler(toolStripDropDownItem_DropDownItemClicked);
            b.DropDownOpened += new EventHandler(toolStripDropDownItem_DropDownOpened);
 
            ToolStripMenuItem m = new ToolStripMenuItem("MenuItem");
            m.DropDown = this.contextMenuStrip1;
            m.DropDownClosed += new EventHandler(toolStripDropDownItem_DropDownClosed);
            m.DropDownItemClicked += new ToolStripItemClickedEventHandler(toolStripDropDownItem_DropDownItemClicked);
            m.DropDownOpened += new EventHandler(toolStripDropDownItem_DropDownOpened);
 
            ToolStripSplitButton sb = new ToolStripSplitButton("SplitButton");
            sb.DropDown = this.contextMenuStrip1;
            sb.DropDownClosed += new EventHandler(toolStripDropDownItem_DropDownClosed);
            sb.DropDownItemClicked += new ToolStripItemClickedEventHandler(toolStripDropDownItem_DropDownItemClicked);
            sb.DropDownOpened += new EventHandler(toolStripDropDownItem_DropDownOpened);
 
            this.toolStrip1.Items.AddRange(new ToolStripItem[] { b, m, sb });
        }
 
        // This method handles the DropDownOpened event from a 
        // ToolStripDropDownItem. It displays the value of the 
        // item's Text property in the form's StatusStrip control.
        void toolStripDropDownItem_DropDownOpened(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
 
            string msg = String.Format("Item opened: {0}", item.Text);
            this.toolStripStatusLabel1.Text = msg;
        }
 
        // This method handles the DropDownItemClicked event from a 
        // ToolStripDropDownItem. It displays the value of the clicked
        // item's Text property in the form's StatusStrip control.
        void toolStripDropDownItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string msg = String.Format("Item clicked: {0}", e.ClickedItem.Text);
            this.toolStripStatusLabel1.Text = msg;
        }
 
        // This method handles the DropDownClosed event from a 
        // ToolStripDropDownItem. It displays the value of the 
        // item's Text property in the form's StatusStrip control.
        void toolStripDropDownItem_DropDownClosed(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
 
            string msg = String.Format("Item closed: {0}", item.Text);
            this.toolStripStatusLabel1.Text = msg;
        }
 
        // This method shows the drop-down for the first item
        // in the form's ToolStrip.
        private void showButton_Click(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = this.toolStrip1.Items[0] as ToolStripDropDownItem;
 
            if (item.HasDropDownItems)
            {
                item.ShowDropDown();
            }
        }
 
        // This method hides the drop-down for the first item
        // in the form's ToolStrip.
        private void hideButton_Click(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = this.toolStrip1.Items[0] as ToolStripDropDownItem;
 
            item.HideDropDown();
        }
 
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.menuItem1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.subItemToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.subItem2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.showButton = new System.Windows.Forms.Button();
            this.hideButton = new System.Windows.Forms.Button();
            this.statusStrip1.SuspendLayout();
            this.contextMenuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // toolStrip1
            // 
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Size = new System.Drawing.Size(292, 25);
            this.toolStrip1.TabIndex = 0;
            this.toolStrip1.Text = "toolStrip1";
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripStatusLabel1});
            this.statusStrip1.Location = new System.Drawing.Point(0, 251);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(292, 22);
            this.statusStrip1.TabIndex = 1;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // toolStripStatusLabel1
            // 
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(38, 17);
            this.toolStripStatusLabel1.Text = "Ready";
            // 
            // contextMenuStrip1
            // 
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.menuItem1ToolStripMenuItem,
            this.menuItem2ToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.contextMenuStrip1.Size = new System.Drawing.Size(146, 48);
            // 
            // menuItem1ToolStripMenuItem
            // 
            this.menuItem1ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.subItemToolStripMenuItem});
            this.menuItem1ToolStripMenuItem.Name = "menuItem1ToolStripMenuItem";
            this.menuItem1ToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.menuItem1ToolStripMenuItem.Text = "Menu Item1";
            // 
            // menuItem2ToolStripMenuItem
            // 
            this.menuItem2ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.subItem2ToolStripMenuItem});
            this.menuItem2ToolStripMenuItem.Name = "menuItem2ToolStripMenuItem";
            this.menuItem2ToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.menuItem2ToolStripMenuItem.Text = "Menu Item 2";
            // 
            // subItemToolStripMenuItem
            // 
            this.subItemToolStripMenuItem.Name = "subItemToolStripMenuItem";
            this.subItemToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.subItemToolStripMenuItem.Text = "Sub Item";
            // 
            // subItem2ToolStripMenuItem
            // 
            this.subItem2ToolStripMenuItem.Name = "subItem2ToolStripMenuItem";
            this.subItem2ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.subItem2ToolStripMenuItem.Text = "Sub Item2";
            // 
            // showButton
            // 
            this.showButton.Location = new System.Drawing.Point(12, 180);
            this.showButton.Name = "showButton";
            this.showButton.Size = new System.Drawing.Size(75, 23);
            this.showButton.TabIndex = 2;
            this.showButton.Text = "Show";
            this.showButton.UseVisualStyleBackColor = true;
            this.showButton.Click += new System.EventHandler(this.showButton_Click);
            // 
            // hideButton
            // 
            this.hideButton.Location = new System.Drawing.Point(12, 209);
            this.hideButton.Name = "hideButton";
            this.hideButton.Size = new System.Drawing.Size(75, 23);
            this.hideButton.TabIndex = 3;
            this.hideButton.Text = "Hide";
            this.hideButton.UseVisualStyleBackColor = true;
            this.hideButton.Click += new System.EventHandler(this.hideButton_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.hideButton);
            this.Controls.Add(this.toolStrip1);
            this.Controls.Add(this.showButton);
            this.Name = "Form1";
            this.Text = "Form1";
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.contextMenuStrip1.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();
        }
 
        #endregion
    }
 
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Код Form1.Designer.cs

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
namespace ToolStripDropDownItemCS
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
 
        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Text = "Form1";
        }
 
        #endregion
    }
}

В чем проблема и как устанить?



0



Администратор

Эксперт .NET

15668 / 12629 / 5003

Регистрация: 17.03.2014

Сообщений: 25,712

Записей в блоге: 1

15.08.2022, 15:53

2

kservice, проблемы перечислены в ошибках компиляции. Во-первых, вам не нужно было копировать код класса Program. Во-вторых, код метода Initi­alizeCompone­nt из Form1.cs нужно аккуратно объединить с Initi­alizeCompone­nt из Form1.Design­er.cs, после чего удалить первый.



1



0 / 0 / 0

Регистрация: 05.03.2016

Сообщений: 62

15.08.2022, 21:17

 [ТС]

3

Помогло частично

Form1. cs
Код Описание Строка
CS0229 Неоднозначность между «Form1.components» и «Form1.components» 111
CS0102 Тип «Form1» уже содержит определение для «components». 21
CS0111 Тип «Form1» уже определяет член «Dispose» с такими же типами параметров. 107
CS0260 Отсутствует модификатор partial в объявлении типа «Form1»; существует другое разделяемое объявление этого типа. 9
CS0229 Неоднозначность между «Form1.components» и «Form1.components» 109

Form1.Designer.cs
Код Описание Строка
CS0229 Неоднозначность между «Form1.components» и «Form1.components» 31
CS0229 Неоднозначность между «Form1.components» и «Form1.components» 16
CS0229 Неоднозначность между «Form1.components» и «Form1.components» 18
CS0229 Неоднозначность между «Form1.components» и «Form1.components» 41
CS0229 Неоднозначность между «Form1.components» и «Form1.components» 45

Не знаю, насколько это «аккуратно»:
Код класса Program закомментировал
код метода Initi­alizeC­ompone­nt из Form1.cs скопировал и вставил в Initi­alizeC­ompone­nt из Form1.Design­­er.cs, после чего первый код тоже закомментировал



0



Администратор

Эксперт .NET

15668 / 12629 / 5003

Регистрация: 17.03.2014

Сообщений: 25,712

Записей в блоге: 1

15.08.2022, 22:21

4

kservice, — удалите поле compo­nents в Form1.cs
— удалите метод Dispose в Form1.cs
— добавьте модификатор partial к классу Form1



1



0 / 0 / 0

Регистрация: 05.03.2016

Сообщений: 62

16.08.2022, 11:14

 [ТС]

5

Спасибо, получилось. Возникает риторический вопрос: зачем такие примеры, которые надо допиливать?
И последний вопрос: как добавить вручную (без применения конструктора) пункт субменю. На рисунке есть Sub Item 1, а как добавить еще 1-2 подпункта в этот же пункт Menu Item 1?

Миниатюры

Ошибки при использовани­­и примера кода из MSDN
 



0



Эксперт .NET

9805 / 5970 / 1410

Регистрация: 25.05.2015

Сообщений: 18,193

Записей в блоге: 14

16.08.2022, 13:22

6

kservice, можете ссылку на статью показать?



0



0 / 0 / 0

Регистрация: 05.03.2016

Сообщений: 62

16.08.2022, 14:17

 [ТС]

7

https://docs.microsoft.com/ru-… esktop-6.0

Сразу после текста «Примеры
В следующем примере кода показано, как отображать и скрывать ToolStripMenuItem элементы управления.»



0



Эксперт .NET

9805 / 5970 / 1410

Регистрация: 25.05.2015

Сообщений: 18,193

Записей в блоге: 14

16.08.2022, 14:34

8

kservice, не, ссылку именно на статью в msdn.
Те ссылки от аккаунта с овердофига сообщений, это от бота, а не от человека.

Добавлено через 9 минут
Там пример типа скопировать, вставить и запустить.

  • Создаёте новый проект winforms.
  • Удаляете файлы формы.
  • Копируете код с сайта.
  • Вставляете его в program.cs вместо того, что там есть.
  • Запускаете.



0



Администратор

Эксперт .NET

15668 / 12629 / 5003

Регистрация: 17.03.2014

Сообщений: 25,712

Записей в блоге: 1

16.08.2022, 14:54

9

Цитата
Сообщение от kservice
Посмотреть сообщение

зачем такие примеры, которые надо допиливать?

Очевидно предполагается минимальное знакомство с Windows Forms и C#. А во вторых, автор примера явно стремился показать всё в рамках одного файла.

Цитата
Сообщение от kservice
Посмотреть сообщение

как добавить вручную (без применения конструктора) пункт субменю

Посмотрите как добавляются существующие и сделайте по аналогии. Подсказка — смотрите Initi­alize методы.



0



0 / 0 / 0

Регистрация: 05.03.2016

Сообщений: 62

16.08.2022, 15:35

 [ТС]

10

Посмотрите как добавляются существующие и сделайте по аналогии.

Мне бы ваши знания. Смотрел и пробовал, и не один раз. Не получается. Пункты переименовать и удалить могу, добавить — нет. Саму идеологию понять не могу. Если подскажите более подробно — буду благодарен.

kservice, не, ссылку именно на статью в msdn.
Те ссылки от аккаунта с овердофига сообщений, это от бота, а не от человека.

Я код брал именно по ссылке, решил, что это и есть MSDN. Как получить ссылку нименно на статью в msdn — не наю



0



Andrey-MSK

1646 / 1121 / 243

Регистрация: 14.08.2018

Сообщений: 3,673

Записей в блоге: 4

17.08.2022, 08:37

11

kservice, Вот так выглядит пример, по вашей ссылке, в проекте, который создаёт студия
Form1.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using System;
using System.Windows.Forms;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private ToolStrip toolStrip1;
        private StatusStrip statusStrip1;
        private ToolStripStatusLabel toolStripStatusLabel1;
        private ContextMenuStrip contextMenuStrip1;
        private ToolStripMenuItem menuItem1ToolStripMenuItem;
        private ToolStripMenuItem menuItem2ToolStripMenuItem;
        private ToolStripMenuItem subItemToolStripMenuItem;
        private ToolStripMenuItem subItem2ToolStripMenuItem;
        private Button showButton;
        private Button hideButton;
        //private System.ComponentModel.IContainer components = null;
 
        public Form1()
        {
            InitializeComponent();
            this.InitializeToolStripDropDownItems();
        }
 
        // This utility method creates and initializes three 
        // ToolStripDropDownItem controls and adds them 
        // to the form's ToolStrip control.
        private void InitializeToolStripDropDownItems()
        {
            ToolStripDropDownButton b = new ToolStripDropDownButton("DropDownButton");
            b.DropDown = this.contextMenuStrip1;
            b.DropDownClosed += new EventHandler(toolStripDropDownItem_DropDownClosed);
            b.DropDownItemClicked += new ToolStripItemClickedEventHandler(toolStripDropDownItem_DropDownItemClicked);
            b.DropDownOpened += new EventHandler(toolStripDropDownItem_DropDownOpened);
 
            ToolStripMenuItem m = new ToolStripMenuItem("MenuItem");
            m.DropDown = this.contextMenuStrip1;
            m.DropDownClosed += new EventHandler(toolStripDropDownItem_DropDownClosed);
            m.DropDownItemClicked += new ToolStripItemClickedEventHandler(toolStripDropDownItem_DropDownItemClicked);
            m.DropDownOpened += new EventHandler(toolStripDropDownItem_DropDownOpened);
 
            ToolStripSplitButton sb = new ToolStripSplitButton("SplitButton");
            sb.DropDown = this.contextMenuStrip1;
            sb.DropDownClosed += new EventHandler(toolStripDropDownItem_DropDownClosed);
            sb.DropDownItemClicked += new ToolStripItemClickedEventHandler(toolStripDropDownItem_DropDownItemClicked);
            sb.DropDownOpened += new EventHandler(toolStripDropDownItem_DropDownOpened);
 
            this.toolStrip1.Items.AddRange(new ToolStripItem[] { b, m, sb });
        }
 
        // This method handles the DropDownOpened event from a 
        // ToolStripDropDownItem. It displays the value of the 
        // item's Text property in the form's StatusStrip control.
        void toolStripDropDownItem_DropDownOpened(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
 
            string msg = String.Format("Item opened: {0}", item.Text);
            this.toolStripStatusLabel1.Text = msg;
        }
 
        // This method handles the DropDownItemClicked event from a 
        // ToolStripDropDownItem. It displays the value of the clicked
        // item's Text property in the form's StatusStrip control.
        void toolStripDropDownItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string msg = String.Format("Item clicked: {0}", e.ClickedItem.Text);
            this.toolStripStatusLabel1.Text = msg;
        }
 
        // This method handles the DropDownClosed event from a 
        // ToolStripDropDownItem. It displays the value of the 
        // item's Text property in the form's StatusStrip control.
        void toolStripDropDownItem_DropDownClosed(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = sender as ToolStripDropDownItem;
 
            string msg = String.Format("Item closed: {0}", item.Text);
            this.toolStripStatusLabel1.Text = msg;
        }
 
        // This method shows the drop-down for the first item
        // in the form's ToolStrip.
        private void showButton_Click(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = this.toolStrip1.Items[0] as ToolStripDropDownItem;
 
            if (item.HasDropDownItems)
            {
                item.ShowDropDown();
            }
        }
 
        // This method hides the drop-down for the first item
        // in the form's ToolStrip.
        private void hideButton_Click(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = this.toolStrip1.Items[0] as ToolStripDropDownItem;
 
            item.HideDropDown();
        }
 
        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing && (components != null))
        //    {
        //        components.Dispose();
        //    }
        //    base.Dispose(disposing);
        //}
    }
}

Form1.Designer.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
namespace WindowsFormsApp1
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
 
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.menuItem1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItem2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.subItemToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.subItem2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.showButton = new System.Windows.Forms.Button();
            this.hideButton = new System.Windows.Forms.Button();
            this.statusStrip1.SuspendLayout();
            this.contextMenuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // toolStrip1
            // 
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Size = new System.Drawing.Size(292, 25);
            this.toolStrip1.TabIndex = 0;
            this.toolStrip1.Text = "toolStrip1";
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripStatusLabel1});
            this.statusStrip1.Location = new System.Drawing.Point(0, 251);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(292, 22);
            this.statusStrip1.TabIndex = 1;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // toolStripStatusLabel1
            // 
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(38, 17);
            this.toolStripStatusLabel1.Text = "Ready";
            // 
            // contextMenuStrip1
            // 
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.menuItem1ToolStripMenuItem,
            this.menuItem2ToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.contextMenuStrip1.Size = new System.Drawing.Size(146, 48);
            // 
            // menuItem1ToolStripMenuItem
            // 
            this.menuItem1ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.subItemToolStripMenuItem});
            this.menuItem1ToolStripMenuItem.Name = "menuItem1ToolStripMenuItem";
            this.menuItem1ToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.menuItem1ToolStripMenuItem.Text = "Menu Item1";
            // 
            // menuItem2ToolStripMenuItem
            // 
            this.menuItem2ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.subItem2ToolStripMenuItem});
            this.menuItem2ToolStripMenuItem.Name = "menuItem2ToolStripMenuItem";
            this.menuItem2ToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.menuItem2ToolStripMenuItem.Text = "Menu Item 2";
            // 
            // subItemToolStripMenuItem
            // 
            this.subItemToolStripMenuItem.Name = "subItemToolStripMenuItem";
            this.subItemToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.subItemToolStripMenuItem.Text = "Sub Item";
            // 
            // subItem2ToolStripMenuItem
            // 
            this.subItem2ToolStripMenuItem.Name = "subItem2ToolStripMenuItem";
            this.subItem2ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.subItem2ToolStripMenuItem.Text = "Sub Item2";
            // 
            // showButton
            // 
            this.showButton.Location = new System.Drawing.Point(12, 180);
            this.showButton.Name = "showButton";
            this.showButton.Size = new System.Drawing.Size(75, 23);
            this.showButton.TabIndex = 2;
            this.showButton.Text = "Show";
            this.showButton.UseVisualStyleBackColor = true;
            this.showButton.Click += new System.EventHandler(this.showButton_Click);
            // 
            // hideButton
            // 
            this.hideButton.Location = new System.Drawing.Point(12, 209);
            this.hideButton.Name = "hideButton";
            this.hideButton.Size = new System.Drawing.Size(75, 23);
            this.hideButton.TabIndex = 3;
            this.hideButton.Text = "Hide";
            this.hideButton.UseVisualStyleBackColor = true;
            this.hideButton.Click += new System.EventHandler(this.hideButton_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.hideButton);
            this.Controls.Add(this.toolStrip1);
            this.Controls.Add(this.showButton);
            this.Name = "Form1";
            this.Text = "Form1";
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.contextMenuStrip1.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();
        }
 
        #endregion
    }
}

Program.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApp1
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}



1



0 / 0 / 0

Регистрация: 05.03.2016

Сообщений: 62

17.08.2022, 12:24

 [ТС]

12

Спасибо, буду разбираться.

Добавлено через 3 часа 10 минут
Сравнил коды ваш и мой и увидел большую разницу. Растолкуйте, как так получается?

Цитата
Сообщение от Andrey-MSK
Посмотреть сообщение

Вот так выглядит пример, по вашей ссылке, в проекте, который создаёт студия

Я тоже делал с помощью студии, а разница громадная.



0



Andrey-MSK

1646 / 1121 / 243

Регистрация: 14.08.2018

Сообщений: 3,673

Записей в блоге: 4

17.08.2022, 16:19

13

Цитата
Сообщение от kservice
Посмотреть сообщение

Растолкуйте, как так получается?

Что получается? Я просто раскидал ту портянку из документации по нужным файлам проекта и всё. В файле Form1.cs закоментировал дубли объявлений, которые по умолчанию генерятся студией в файле Form1.Designer.cs:

C#
1
private System.ComponentModel.IContainer components = null;

и

C#
1
2
3
4
5
6
7
8
protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }
    base.Dispose(disposing);
}

Вот и всё…



1



Возможно, вам также будет интересно:

  • Ошибка cs0120 для нестатического поля метода или свойства требуется ссылка на объект
  • Ошибка cs0115 form1 dispose bool не найден метод пригодный для переопределения
  • Ошибка cs0106 модификатор public недопустим для этого элемента
  • Ошибка cs0103 visual studio
  • Ошибка cs0021 не удается применить индексирование через к выражению типа int

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии