AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 30.01.2016, 17:21   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
goshoom: X++ to CIL: Object must implement IConvertible
Источник: http://dev.goshoom.net/en/2016/01/x-...-iconvertible/
==============

Somebody asked in Dynamics User Group forum about an error thrown by RetailCommonWebAPI running in a batch in AX 2012 (RetailCommonWebAPI in batch mode). I don’t want to discuss that particular problem here, but I want to show the underlying cause, because it’s actually quite tricky.

What I’m discussing below is related to CIL generated from X++, therefore if you want to try the sample code, make sure that you run it in CIL. It doesn’t require running in batch.

Let’s start with a simple piece of X++ code. It creates a Hashtable (using .NET Interop) and passes it to the constructor of another hash table. (I don’t bother adding any data to the hash table, because it’s not necessary for the demonstration.) This code works without any problem.

System.Collections.Hashtable t1 = new System.Collections.Hashtable();System.Collections.Hashtable t2 = new System.Collections.Hashtable(t1);






Now let’s change a single thing – the type of the first variable will be defined as CLRObject instead of Hashtable. Note that the content of the variable is exactly the same as before.

CLRObject t1 = new System.Collections.Hashtable();System.Collections.Hashtable t2 = new System.Collections.Hashtable(t1);






If you run this code (in CIL), you’ll get an error:

System.InvalidCastException: Object must implement IConvertible. at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)It’s an interesting result. I would expect the call to fail, because there is no Hashtable’s constructor accepting an object (System.Object), but it’s not the reason. It’s referring to a call to Convert.ChangeType(), but where did it come from?

The answer can’t be found in X++; you have to look at the generated CIL code. This is what I got from the first snippet (after decompiling CIL to C#):

t2 = new Hashtable((IDictionary) t1);






Hashtable has two constructors accepting a single parameter: one takes capacity (int) and one takes elements in the form of a dictionary (such as a hash table). We want to use the latter and that’s exactly what happens.

Now look at CIL generated for the other snippet:

t2 = new Hashtable((int) Convert.ChangeType(t1, typeof(int)));






This is unexpected and incorrect code. The generator of CIL from X++ somehow decided to use the constructor accepting int and it’s trying to convert t1 to int. It must fail, because there is no conversion from Hashtable to int. And even if it succeeded, we would get an empty Hashtable (which is not what we would want, if t1 contained some values).

If the CIL generator doesn’t know the underlying type, it shouldn’t try to guess it, because it’s likely to fail and we end up with weird and unpredictable errors. A compile-time failure would be a much safer approach.

Just for completeness, this is how CIL looks like if you declare the variable as System.Collections.IDictionary (as I suggested in the discussion forum):

t2 = new Hashtable(t1);






Because the type is exactly matching the expected type, there is neither type casting nor any conversion.



Источник: http://dev.goshoom.net/en/2016/01/x-...-iconvertible/
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
goshoom: Tips for CIL debugging: Collection classes Blog bot DAX Blogs 0 11.01.2015 18:12
goshoom: Tips for CIL debugging: No variables displayed Blog bot DAX Blogs 0 11.01.2015 18:12
X++ to CIL Blog bot DAX Blogs 0 01.04.2013 14:11
X++: X++ Arrays Behave Differently in .NET CIL, in Dynamics AX 2012 Blog bot DAX Blogs 0 17.09.2012 23:11

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 01:07.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.