InvalidCastException while casting to OrganizationServiceContext

情到浓时终转凉″ 提交于 2020-06-28 03:42:27

问题


I have a early bound class generated by CrmSvcUtil:

public partial class CustomerCrmServiceContext : Microsoft.Xrm.Sdk.Client.OrganizationServiceContext
{
  ...
  ...
}

Then I have a class like this (short version):

public abstract class PluginClass<T, C> : PluginClassBase<T> where T : Entity where C : OrganizationServiceContext
{
        protected new C ServiceContext;

        protected PluginClass(IOrganizationService service, ITracingService tracer) : base(service, tracer)
        {
            ServiceContext = (C)base.ServiceContext;
        }
}

And the Base class like this:

public abstract class PluginClassBase: IDisposable
{
    ...
    ...
    protected readonly OrganizationServiceContext ServiceContext;
    ...
    ...
}

I am using this class like this:

public class DoWomethingWorkerPlugin : PluginClass<account, CustomerCrmServiceContext>
{
  ...
}

My Problem is the following statement:

ServiceContext = (C)base.ServiceContext;

This throws an InvalidCastException saying:

"Unable to cast object of type 'Microsoft.Xrm.Sdk.Client.OrganizationServiceContext' to type 'Customer.DataModel.CustomerCrmServiceContext"

I'm confused since the generated class "CustomerCrmServiceContext" has the base type "OrganizationServiceContext" and therefore the cast should work.

Does anybody have an idea what can cause an InvalidCastException when base type is the same?


回答1:


Although a CustomerCrmServiceContext is an OrganizationServiceContext, the opposite isn't true, which is why you're getting the exception.

A cast cannot magically change an object's type at runtime.

By using a cast, your essentially telling the compiler "Although you think this object is SomeBaseType, I know that, at runtime, it will always be an instance of SomeDerivedType so please treat it as such".

If it transpires that at runtime, the object isn't the type that you have tried to cast to, you will get an InvalidCastException, and an OrganizationServiceContext isn't a CustomerCrmServiceContext.



来源:https://stackoverflow.com/questions/62535340/invalidcastexception-while-casting-to-organizationservicecontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!