iceContext时发生InvalidCastExceptio

iceContext时发生InvalidCastExceptio

本文介绍了强制转换为OrganizationServiceContext时发生InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由CrmSvcUtil生成的早期绑定类:

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;
        }
}

基类如下:

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

我正在使用此类

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

我的问题如下:

ServiceContext = (C)base.ServiceContext;

这会引发InvalidCastException说:

This throws an InvalidCastException saying:

我很困惑,因为生成的类 CustomerCrmServiceContext具有基本类型 OrganizationServiceContext;

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

有人知道在基本类型相同的情况下会导致InvalidCastException吗?

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

推荐答案

尽管 CustomerCrmServiceContext OrganizationServiceContext ,但事实并非如此,

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.

通过强制类型转换,本质上告诉编译器,尽管您认为该对象是 SomeBaseType ,但我知道,在运行时,它将始终是 SomeDerivedType的实例,请这样处理。

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".

如果在运行时显示该对象不是您尝试投射的类型到此,您将得到 InvalidCastException ,而 OrganizationServiceContext 不是 CustomerCrmServiceContext

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.

这篇关于强制转换为OrganizationServiceContext时发生InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:13