Dnspy ошибки при компиляции


Go to dotnet


r/dotnet

.NET Community, if you are using C#, VB.NET, F#, or anything running with .NET… you are at the right place!




Members





Online



[DnSpy] how do I compile while ignoring errors?

I’m editing a DLL and all I am doing is changing one line, unfortunately thousands of other lines in this file are giving an erorr (it has nothing to do with what I»m changing. If I decompile then compile it will give this error regardless.)

I don’t want to go through thousands of lines fixing their hundreds of errors. How do I get DnSpy to ignore it?

Identifier Expected (base.ctor)[]

You will often get this error when editing a class constructor. Within the method, you should find a line that looks like:

base..ctor(...);

You need to move this call up next to the constructor signature. So if you have:

public SomeClass(x, y, z) 
{
    ...
    base..ctor(x, y, z);
    ...
}

You should change it to:

public SomeClass(x, y, z) : base(x, y, z) 
{
    ...
}

The type X already contains a definition for Y[]

(The newest nightly builds of dnSpy no longer have this issue)

Sometimes when editing a class with dnSpy, it will duplicate one or more of the class variables after you compile your changes. This can cause many problems, one of which being when you try to make your next edit, you will get an error because of the duplicate existing.

When you scroll down to the list of class variables, and find the one that was duplicated, the version that is further towards the bottom is the duplicate, while the one further up is the original one.

If the method you modified did not make use of any of the variables that got duplicated, it is safe to just delete the duplicate and continue with your edits. However, if any of those duplicates were present in the modified method, then don’t delete it yet!! If you delete it, the method you modified will get destroyed, and will become something like this:

DecompileError.PNG

And if you save the module you will get an error like this:

SaveModuleError.PNG

If this ever happens, use the Undo function to revert your changes immediately, otherwise your DLL will be permanently broken. To avoid this happening, first note the Token hex number that appears over top the duplicate variable, and over top the original variable. Then go back to the method you modified and find every place where the variable is used.

IL Edit those lines. Each of those places will be pointing to the duplicate, so you want to click on them and change them back to the original (you can tell the two apart based on the token numbers). Once you’ve changed all of them back to the original, then you can safely delete the duplicate from the class and continue with your editing.

Cannot convert from X to X[]

(The newest nightly builds of dnSpy no longer have this issue)

This error comes up most often when passing the current class as an argument to another class or function via the «this» keyword. So the lines giving this error will be something like:

this.whatever = new Something(this, x, y, z);

We want to change the «this» keyword temporarily to «null»:

this.whatever = new Something(null, x, y, z);

This will stop the errors and will allow you to compile. However, we can’t leave them as null! We need to change all of those «null» keywords back to «this». This will be done by going back to each of the lines that we changed to null and IL editing them.

In the IL Edit window, the null keyword will appear as «ldnull», you just need to change that to «ldarg.0», and it should become «this» again.

X does not implement interface member Y[]

(The newest nightly builds of dnSpy no longer have this issue)

You may encounter this error when editing C# methods on a class that implements an interface. An interface requires a certain set of methods to be present in the class, but when you are editing a method in C#, the class becomes a «partial class» where all the methods other than the one you are editing get hidden. This triggers the error because the partial class no longer conforms to the interface’s requirements.

If you look up at the signature for the class/partial class, the interfaces will be the ones after the colon that are colored as gray text. Just remove the interface temporarily (make sure you remember what it is called), and you will be able to compile. However, once you’ve compiled the method and are done with your edits, you need to add the interface back!

To do this:

  • Right click on the class name.
  • Choose «Edit Type».
  • Go to the «Interfaces» tab.
  • Click «Add…»
  • Click «Type»
  • Search for the name of the interface you deleted, select it, and click «OK».

The type or namespace name X could not be found[]

This error will appear if you’re missing a using directive. Sometimes when editing a method, dnSpy will fail to copy over all the «using» imports that the class actually contains (found at the very top of the file). Just copy all of the using directives from the original class, and paste them into the Edit Code window, so you don’t miss any.

Operator is ambiguous on operands of type Vector3 and Vector2[]

To solve this, convert the Vector2 in the line that’s throwing an error into a Vector3. For example:

// This will throw an error
v2 + v3; 

// This will compile fine
new Vector3(v2.x, v2.y, 0) + v3; 

Or in any Other Case…[]

Sometimes there’s some error in the method that you just don’t know how to get around, or it’s just a particularly annoying method to edit because it has a large number of lines that have errors. One good general workaround for many situations is to make a new method with your code changes, then IL edit in a call to the new method into the original method you couldn’t edit with C#. This requires just two IL lines:

ldarg.0
call    (reference to your new function)

You can right click in the IL editor to see options for adding new lines/instructions.

Identifier Expected (base.ctor)[]

You will often get this error when editing a class constructor. Within the method, you should find a line that looks like:

base..ctor(...);

You need to move this call up next to the constructor signature. So if you have:

public SomeClass(x, y, z) 
{
    ...
    base..ctor(x, y, z);
    ...
}

You should change it to:

public SomeClass(x, y, z) : base(x, y, z) 
{
    ...
}

The type X already contains a definition for Y[]

(The newest nightly builds of dnSpy no longer have this issue)

Sometimes when editing a class with dnSpy, it will duplicate one or more of the class variables after you compile your changes. This can cause many problems, one of which being when you try to make your next edit, you will get an error because of the duplicate existing.

When you scroll down to the list of class variables, and find the one that was duplicated, the version that is further towards the bottom is the duplicate, while the one further up is the original one.

If the method you modified did not make use of any of the variables that got duplicated, it is safe to just delete the duplicate and continue with your edits. However, if any of those duplicates were present in the modified method, then don’t delete it yet!! If you delete it, the method you modified will get destroyed, and will become something like this:

DecompileError.PNG

And if you save the module you will get an error like this:

SaveModuleError.PNG

If this ever happens, use the Undo function to revert your changes immediately, otherwise your DLL will be permanently broken. To avoid this happening, first note the Token hex number that appears over top the duplicate variable, and over top the original variable. Then go back to the method you modified and find every place where the variable is used.

IL Edit those lines. Each of those places will be pointing to the duplicate, so you want to click on them and change them back to the original (you can tell the two apart based on the token numbers). Once you’ve changed all of them back to the original, then you can safely delete the duplicate from the class and continue with your editing.

Cannot convert from X to X[]

(The newest nightly builds of dnSpy no longer have this issue)

This error comes up most often when passing the current class as an argument to another class or function via the «this» keyword. So the lines giving this error will be something like:

this.whatever = new Something(this, x, y, z);

We want to change the «this» keyword temporarily to «null»:

this.whatever = new Something(null, x, y, z);

This will stop the errors and will allow you to compile. However, we can’t leave them as null! We need to change all of those «null» keywords back to «this». This will be done by going back to each of the lines that we changed to null and IL editing them.

In the IL Edit window, the null keyword will appear as «ldnull», you just need to change that to «ldarg.0», and it should become «this» again.

X does not implement interface member Y[]

(The newest nightly builds of dnSpy no longer have this issue)

You may encounter this error when editing C# methods on a class that implements an interface. An interface requires a certain set of methods to be present in the class, but when you are editing a method in C#, the class becomes a «partial class» where all the methods other than the one you are editing get hidden. This triggers the error because the partial class no longer conforms to the interface’s requirements.

If you look up at the signature for the class/partial class, the interfaces will be the ones after the colon that are colored as gray text. Just remove the interface temporarily (make sure you remember what it is called), and you will be able to compile. However, once you’ve compiled the method and are done with your edits, you need to add the interface back!

To do this:

  • Right click on the class name.
  • Choose «Edit Type».
  • Go to the «Interfaces» tab.
  • Click «Add…»
  • Click «Type»
  • Search for the name of the interface you deleted, select it, and click «OK».

The type or namespace name X could not be found[]

This error will appear if you’re missing a using directive. Sometimes when editing a method, dnSpy will fail to copy over all the «using» imports that the class actually contains (found at the very top of the file). Just copy all of the using directives from the original class, and paste them into the Edit Code window, so you don’t miss any.

Operator is ambiguous on operands of type Vector3 and Vector2[]

To solve this, convert the Vector2 in the line that’s throwing an error into a Vector3. For example:

// This will throw an error
v2 + v3; 

// This will compile fine
new Vector3(v2.x, v2.y, 0) + v3; 

Or in any Other Case…[]

Sometimes there’s some error in the method that you just don’t know how to get around, or it’s just a particularly annoying method to edit because it has a large number of lines that have errors. One good general workaround for many situations is to make a new method with your code changes, then IL edit in a call to the new method into the original method you couldn’t edit with C#. This requires just two IL lines:

ldarg.0
call    (reference to your new function)

You can right click in the IL editor to see options for adding new lines/instructions.

AndnixSH

  • #1


Вы получаете такие ошибки при попытке компиляции?

1540314721232.png

Попробуйте редактировать только метод вместо всего класса

Все еще получаете ошибку? следуйте простым шагам, чтобы исправить это.

Двойной щелчок на ошибках, он укажет вам на метод. Удалите все методы, вызвавшие ошибку, затем скомпилируйте

1540314734932.png

Типичная ошибка — генерируется код <> f__mg $ cache0, удалите его
[Глобальный :: System.Runtime.CompilerServices.CompilerGenerated]
частный статический глобальный :: System.Action <> f__mg $ cache0;

1540314745213.png

Готово!

1540314751685.png

Последнее редактирование: 2 Марта, 2021

  • #2

Я думаю, что единственный способ, которым вы не можете это исправить (и вы должны использовать IL Edit), это когда вы получаете ошибки с методами Backing Fields, исправьте меня, если я ошибаюсь

Nardo7

APK Fanatic Уровень 5️⃣

  • #3

Хороший учебник как всегда @AndnixSH я всегда решаю проблему, как вы сказали, ожидайте один раз: я нашел игру (единство), и я сделал Меню MOD но я обнаружил проблему с графикой … в игре есть только модальное окно, которое не кликабельно, поэтому я застрял. Я попытался добавить еще одну внешнюю библиотеку с этими методами (Window, DoWindow, INTERNAL_CALL_DoWindow), но две графики не связаны, поэтому она не работает. Поэтому я попытался принудительно добавить эти методы, но я всегда получаю это в кодах ошибок:
(модифицированный класс)
[GeneratedByOldBindingsGenerator]
[MethodImpl (4096)]
(модифицированный метод)
[Глобальный :: UnityEngine.Scripting.GeneratedByOldBindingsGenerator]
[Глобального :: System.Runtime.CompilerServices.MethodImpl (4096)]

Я могу удалить и добавить эти методы для обработки окна на графике, но когда я запускаю игру, игра останавливается.

AndnixSH

  • #4

Я думаю, что единственный способ, которым вы не можете это исправить (и вы должны использовать IL Edit), это когда вы получаете ошибки с методами Backing Fields, исправьте меня, если я ошибаюсь

У вас есть пример этого?

Хороший учебник как всегда @AndnixSH я всегда решаю проблему, как вы сказали, ожидайте один раз: я нашел игру (единство), и я сделал Меню MOD но я обнаружил проблему с графикой … в игре есть только модальное окно, которое не кликабельно, поэтому я застрял. Я попытался добавить еще одну внешнюю библиотеку с этими методами (Window, DoWindow, INTERNAL_CALL_DoWindow), но две графики не связаны, поэтому она не работает. Поэтому я попытался принудительно добавить эти методы, но я всегда получаю это в кодах ошибок:
(модифицированный класс)
[GeneratedByOldBindingsGenerator]
[MethodImpl (4096)]
(модифицированный метод)
[Глобальный :: UnityEngine.Scripting.GeneratedByOldBindingsGenerator]
[Глобального :: System.Runtime.CompilerServices.MethodImpl (4096)]

Я могу удалить и добавить эти методы для обработки окна на графике, но когда я запускаю игру, игра останавливается.

Я действительно не знаю почему. Я только модифицирую свой собственный путь без внешней библиотеки, так что я не знаю

dnSpy — How to fix compiler error on main.g.cs

How to fix compiler error in maingcs from Andnix on Vimeo.

Are you getting errors like this when
trying to compile?

Try edit only Method instead whole Class

Still getting error? follow the
simple steps to fix it.

Double click on errors, It will
point you to the method. Remove all method that caused error then compile

Common error is
generated code <>f__mg$cache0, remove it

 [global::System.Runtime.CompilerServices.CompilerGenerated]
 
private static global::System.Action<string<>f__mg$cache0;

Done!

Popular Posts

[Discontinued] VMOS Pro Global/CN Free Custom ROMs | Android 4.4.4, 5.1.1, 7.1.2 | ROOT | Gapps | Xposed | (NO VIP NEEDED)

Image

Discontinued. No more updates Due to anti-piracy system VMOS made to prevents root from working correctly with custom ROMs, this project has been discontinued. I wasted a day trying to fix root, but i have no luck. Root is just broken or seems to be disabled. I recommended you to use modded APK of VMOS Pro instead, It is much easier to use. Don’t trust anti-virus if mod detected as virus VMOS Pro was protected so i wasn’t able to modify APK. Instead, I made a custom ROM as a zip file for VMOS Pro that includes Superuser and Xposed.   If you wonder why VMOS team released pro version, they got suspended from making money from ads so they can only make money from VIP service. If you support them, consider to pay VIP per month to keep them up and you can use their official ROM with switchable root option YOU CANNOT INSTALL ANY OTHER ROMS SUCH AS SAMSUNG, HUAWEI, ETC THAT ARE NOT MADE FOR VMOS. VMOS ROM INSTALLATION IS FOR VMOS ROM ONLY. PLEASE DO NOT BE DUMB, THANKS! Downl

[TOOL] Unity Assets Bundle Extractor

Image

Unity .assets and AssetBundle editor UABE is an editor for Unity 3.4+/4/5/2017/2018 .assets and AssetBundle files. It can create standalone mod installers from changes to .assets and/or bundles. Type information extracted from Unity is used in order to generate text representations of various asset types. Custom MonoBehaviour types also are supported. There are multiple plugins to convert Unity assets from/to common file formats : The Texture plugin can export and import .png and .tga files and decode&encode most texture formats used by Unity. The TextAsset plugin can export and import .txt files. The AudioClip plugin can export uncompressed .wav files from U5’s AudioClip assets using FMOD, .m4a files from WebGL builds and Unity 4 sound files. The Mesh plugin can export .obj and .dae (Collada) files, also supporting rigged SkinnedMeshRenderers. The MovieTexture plugin can export and import .ogv (Ogg Theora) files.

0 / 0 / 0

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

Сообщений: 16

1

.NET 3.x

29.04.2018, 11:02. Показов 4677. Ответов 3


Декомпилировал Assembly-CSharp с помощью DnSpy, и когда я хочу скомпилировать мне выдаёт кучу ошибок что требуется идентификатор.

Миниатюры

Ошибки при компиляции сборки декомпилированной DnSpy
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

29.04.2018, 11:02

3

Эксперт .NET

6268 / 3896 / 1567

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

Сообщений: 9,187

29.04.2018, 11:05

2

Исправляйте ошибки компиляции. Например у вас на скрине это бывший switch превращенный компилятором в Dictionary<string, int>. Можно либо переделать обратно в switch, либо оставить как есть переименовав имя словаря…

0

0 / 0 / 0

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

Сообщений: 16

29.04.2018, 11:40

 [ТС]

3

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

Исправляйте ошибки компиляции. Например у вас на скрине это бывший switch превращенный компилятором в Dictionary<string, int>. Можно либо переделать обратно в switch, либо оставить как есть переименовав имя словаря…

Я сейчас не понял не слова из твоего текста, можно по подробнее пожалуйста.

0

Эксперт .NET

6268 / 3896 / 1567

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

Сообщений: 9,187

29.04.2018, 14:07

4

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

Я сейчас не понял не слова из твоего текста, можно по подробнее пожалуйста.

Подробнее в любом учебнике по C#.

1

The ‘ConnectionState’ exists in both ‘System.Data.Common, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ and ‘System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

bool flag2 = this.sqlite_conn.State != ConnectionState.Open;
            if (flag2)
            {
                this.sqlite_conn.Close();
                this.sqlite_conn.Open();
            }

Getting above error in this line of code while using dnspy.
Error code is CS0433 from main.cs

AndnixSH


  • #1


Вы получаете такие ошибки при попытке компиляции?

1540314721232.png

Попробуйте редактировать только метод вместо всего класса

Все еще получаете ошибку? следуйте простым шагам, чтобы исправить это.

Двойной щелчок на ошибках, он укажет вам на метод. Удалите все методы, вызвавшие ошибку, затем скомпилируйте

1540314734932.png

Типичная ошибка — генерируется код <> f__mg $ cache0, удалите его
[Глобальный :: System.Runtime.CompilerServices.CompilerGenerated]
частный статический глобальный :: System.Action <> f__mg $ cache0;

1540314745213.png

Готово!

1540314751685.png

Последнее редактирование: 2 Марта, 2021

Sbenny


  • #2

Я думаю, что единственный способ, которым вы не можете это исправить (и вы должны использовать IL Edit), это когда вы получаете ошибки с методами Backing Fields, исправьте меня, если я ошибаюсь :)

Nardo7

Nardo7

APK Fanatic Уровень 5️⃣


  • #3

Хороший учебник как всегда @AndnixSH я всегда решаю проблему, как вы сказали, ожидайте один раз: я нашел игру (единство), и я сделал Меню MOD но я обнаружил проблему с графикой … в игре есть только модальное окно, которое не кликабельно, поэтому я застрял. Я попытался добавить еще одну внешнюю библиотеку с этими методами (Window, DoWindow, INTERNAL_CALL_DoWindow), но две графики не связаны, поэтому она не работает. Поэтому я попытался принудительно добавить эти методы, но я всегда получаю это в кодах ошибок:
(модифицированный класс)
[GeneratedByOldBindingsGenerator]
[MethodImpl (4096)]
(модифицированный метод)
[Глобальный :: UnityEngine.Scripting.GeneratedByOldBindingsGenerator]
[Глобального :: System.Runtime.CompilerServices.MethodImpl (4096)]

Я могу удалить и добавить эти методы для обработки окна на графике, но когда я запускаю игру, игра останавливается.

AndnixSH


  • #4

Я думаю, что единственный способ, которым вы не можете это исправить (и вы должны использовать IL Edit), это когда вы получаете ошибки с методами Backing Fields, исправьте меня, если я ошибаюсь :)

У вас есть пример этого?

Хороший учебник как всегда @AndnixSH я всегда решаю проблему, как вы сказали, ожидайте один раз: я нашел игру (единство), и я сделал Меню MOD но я обнаружил проблему с графикой … в игре есть только модальное окно, которое не кликабельно, поэтому я застрял. Я попытался добавить еще одну внешнюю библиотеку с этими методами (Window, DoWindow, INTERNAL_CALL_DoWindow), но две графики не связаны, поэтому она не работает. Поэтому я попытался принудительно добавить эти методы, но я всегда получаю это в кодах ошибок:
(модифицированный класс)
[GeneratedByOldBindingsGenerator]
[MethodImpl (4096)]
(модифицированный метод)
[Глобальный :: UnityEngine.Scripting.GeneratedByOldBindingsGenerator]
[Глобального :: System.Runtime.CompilerServices.MethodImpl (4096)]

Я могу удалить и добавить эти методы для обработки окна на графике, но когда я запускаю игру, игра останавливается.

Я действительно не знаю почему. Я только модифицирую свой собственный путь без внешней библиотеки, так что я не знаю

AndnixSH

AndnixSH

PMT Elite Modder


Original poster

Staff member

Modding-Team


  • #1


Are you getting errors like this when trying to compile?

1540314551491.png

Try edit only Method instead whole Class

Still getting error? follow the simple steps to fix it.

Double click on errors, It will point you to the method. Remove all method that caused error then compile

1540314562779.png

Common error is generated code <>f__mg$cache0, remove it
[global::System.Runtime.CompilerServices.CompilerGenerated]
private static global::System.Action<string> <>f__mg$cache0;

1540314568977.png

Done!

1540314575419.png

Last edited: Mar 2, 2021

  • Dnsapi dll ошибка как исправить
  • Dns сервер ошибка 5504
  • Dns сервер обнаружил критическую ошибку active directory проверьте работоспособность active directory
  • Dns сервер недоступен как исправить ошибку
  • Dns сервер не отвечает ошибка при подключении интернета