最新消息:ww12345678 的部落格重装上线,希望大家继续支持。

.NET类型的“is”和“as”运算符 / ‘is’ and ‘as’ operators with .NET types

网络文摘 William 97浏览 0评论
I recently ran into an unfortunate limitation of .NET Interop from X++ (in D365FO). I wanted to check if an X++ object is of a given type, nevertheless the type used for the variable declaration was a .NET interface. Here is an example:
using Microsoft.Dynamics.ApplicationSuite.FinancialManagement.Currency.Framework;
 
void demo(IExchangeRateProvider _provider)
{
    if (_provider is ExchangeRateProviderCBOE) {}
}
Exchange rate providers are X++ classing implementing IExchangeRateProvider interface and I wanted to check if the object I received was a particular provider (namely ExchangeRateProviderCBOE class or its child). Unfortunately this ended up with a compilation error:
The operand on the left side of the ‘is’ or ‘as’ operator must be a table, class, or form.
As I tested, neither managed interfaces nor managed classes (such as System.Object) can be used on the left side of ‘is’ and ‘as’ operators. I solved the problem by using Type.IsAssignableFrom() method. Simply using the ‘is’ operator would be nicer, but this does the job too.
void demo(IExchangeRateProvider _provider)
{
    System.Object providerObj = _provider;
    if (providerObj.GetType().IsAssignableFrom(new ExchangeRateProviderCBOE().GetType())) {}
}
Note that the problem is only with the left side of the operators, e.g. when you want to check whether a managed type is this or that. Using the ‘is’ operator to check if an instance of an X++ class implements a managed interface works without problems.
Object obj = new ExchangeRateProviderCBOE();
if (obj is IExchangeRateProvider) {}
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址