类型'customObject'的对象不能转换为类型'customObject“ [英] Object of type 'customObject' cannot be converted to type 'customObject'

查看:110
本文介绍了类型'customObject'的对象不能转换为类型'customObject“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误,当我调用自定义对象结果
类型customObject'的对象不能转换为类型'customObject'。

以下是该方案的时候,我得到这个错误:


  • 我动态调用DLL中的方法。

  • 加载程序集

  • 的CreateInstance ....

当调用MethodInfo.Invoke()传递整型,字符串作为我的方法的参数正常工作=>没有异常抛出。

但是,如果我试图通过我自己的自定义类的一个对象作为参数,然后我得到一个的ArgumentException 例外,它不是任何一个 ArgumentOutOfRangeException ArgumentNullException

类型customObject'的对象不能转换为类型'customObject'。

我在Web应用程序这样做。

包含此方法的类文件是在不同的项目中。另外,自定义对象是在同一个文件一个单独的类。

有没有一个叫这样的事情静电装配在我的code。我试图动态调用一个WebMethod。此的webmethod是具有customObject类型作为输入参数。因此,当我调用的WebMethod我动态创建代理装配和所有。从同一个程序集我试图创建cusotm对象assinging值其属性的一个实例,然后通过这个对象作为参数,调用方法。一切都是动态的,没有什么是创建静态.. :(

添加参考没有使用。
下面是一个示例code我试图创建它。

 公共静态对象CallWebService(字符串webServiceAsmxUrl,弦乐服务名,字符串methodName中,对象[]参数)
    {
        System.Net.WebClient客户端=新System.Net.WebClient();
        // - 连接到Web服务
        使用(的System.IO.Stream流= client.OpenRead(webServiceAsmxUrl +?WSDL))
        {
            // - 现在读描述服务的WSDL文件。
            ServiceDescription描述= ServiceDescription.Read(流);
            /////加载DOM /////////
            // - 初始化服务描述进口国。
            ServiceDescriptionImporter进口商=新ServiceDescriptionImporter();
            importer.ProtocolName =SOAP12; //使用SOAP 1.2。
            importer.AddServiceDescription(描述,NULL,NULL);
            // - 生成代理客户端。 importer.Style = ServiceDescriptionImportStyle.Client;
            // - 生成的属性重新present的原始值。
            进口商codeGenerationOptions =的System.Xml.Serialization codeGenerationOptions.GenerateProperties。;
            // - 初始化code-DOM树成,我们将导入服务。
            codeNamespace nmspace =新的codeNamespace();
            codeCompileUnit 1单元=新的codeCompileUnit();
            unit1.Namespaces.Add(nmspace);
            // - 将服务导入到code-DOM树。这将创建代理code
            // - 使用该服务。
            ServiceDescriptionImportWarnings警告= importer.Import(nmspace,1单元);
            如果(警告== 0)// - 如果为零,那么,我们是好去
            {
                // - 生成代理code
                codeDomProvider provider1 = codeDomProvider.CreateProvider(CSHARP);
                // - 编译与适当的引用装配代理
                字符串[] = assemblyReferences新的字符串[5] {System.dll中,System.Web.Services.dll,System.Web.dll程序,system.xml.dll的,System.Data.dll中 };
                CompilerParameters PARMS =新CompilerParameters(assemblyReferences);
                CompilerResults结果= provider1.CompileAssemblyFromDom(PARMS,1单元);
                // - 检查是否存在错误
                如果(results.Errors.Count大于0)
                {
                    StringBuilder的SB =新的StringBuilder();
                    的foreach(CompilerError哎呀在results.Errors)
                    {
                        sb.AppendLine(========编译器错误============);
                        sb.AppendLine(oops.ErrorText);
                    }
                    抛出新System.ApplicationException(编译出错调用webservice的。+ sb.ToString());
                }
                // - 最后,调用Web服务方法
                键入foundType = NULL;
                键入[]类型= results.CompiledAssembly.GetTypes();
                的foreach(在类型类型类型)
                {
                    如果(type.BaseType == typeof运算(System.Web.Services.Protocols.SoapHttpClientProtocol))
                    {
                        Console.WriteLine(type.ToString());
                        foundType =类型;
                    }
                }                对象wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString());
                MethodInfo的MI = wsvcClass.GetType()实现getMethod(方法名)。
                返回mi.Invoke(wsvcClass,参数);
            }
            其他
            {
                返回null;
            }
        }
    }

我找不到任何静态在我做什么。

任何帮助是极大AP preciated。

问候,
Phani库马尔PV


解决方案

让我试着解释最有可能的原因问题来在我的方法。

当我援引称为在web服务,我试图通过为要求,以功能CallWebServiceargs []为参数方法名组装方法
这ARGS []时,通过将成功合作,当我试图通过正常的参数,如原始的类型,包括字符串。

但是,这是我做的,当我试图通过自定义对象作为参数。<​​/ P>

这是在做这三件事情。


  1. 创建该类型的CallWebService功能(使用反射)以外的一个目的。当我这样做,这样会发生什么是内部一个临时的DLL名称创建customobject的一个实例。

  2. 一旦我设定的设置对象的属性和对面CallWebService功能,将其作为args数组中的对象。

  3. 我累了创建动态的dll来创建Web服务的一个实例。

    对象wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString());


当我终于尝试的动态组装的创建的实例调用的方法
 我试图传递是在通过ARGS财产1,2步创建的customobject。

在CLR的尝试,看看是否能作为输入和被调用的方法通过customobject是从同一个DLL调用的时间。

这显然不是从实现完成的方式。

所以以下是应该被用来解决这个问题的办法
我需要创建与我用来创建Web服务的实例相同的程序集的自定义对象组装。

我完全实施这一做法,并制定了罚款

  MethodInfo的M = type.GetMethod(方法名);
的ParameterInfo [] PM = m.GetParameters();
对象ob;
[对象] Y =新对象[1];
的foreach(在下午的ParameterInfo paraminfo)
{
    OB = this.webServiceAssembly.CreateInstance(paraminfo.ParameterType.Name);    //一些垃圾逻辑来获取设置的值到自定义对象的属性
    的foreach(的PropertyInfo propera在ob.GetType()的GetProperties())
    {
        如果(propera.Name ==AppGroupid)
        {
            propera.SetValue(OB,SQL2005Tools,NULL);
        }
        如果(propera.Name ==APPID)
        {
            propera.SetValue(OB,%,NULL);
        }
    }
    Y [0] = OB;
}

I receive the following error when I invoke a custom object
"Object of type 'customObject' cannot be converted to type 'customObject'."

Following is the scenario when I am get this error:

  • I invoke a method in a dll dynamically.
  • Load an assembly
  • CreateInstance....

When calling MethodInfo.Invoke() passing int, string as a parameter for my method works fine => No exceptions are thrown.

But if I try and pass one of my own custom class objects as a parameter, then I get an ArgumentException exception, and it is not either an ArgumentOutOfRangeException or ArgumentNullException.

"Object of type 'customObject' cannot be converted to type 'customObject'."

I am doing this in a web application.

The class file containing the method is in a different project. Also the custom object is a separate class in the same file.

There is no such thing called a static assembly in my code. I am trying to invoke a webmethod dynamically. this webmethod is having the customObject type as an input parameter. So when i invoke the webmethod i am dynamically creating the proxy assembly and all. From the same assembly i am trying to create an instance of the cusotm object assinging the values to its properties and then passing this object as a parameter and invoking the method. everything is dynamic and nothing is created static.. :(

add reference is not used. Following is a sample code i tried to create it

public static object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args) 
    { 
        System.Net.WebClient client = new System.Net.WebClient(); 
        //-Connect To the web service 
        using (System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl")) 
        { 
            //--Now read the WSDL file describing a service. 
            ServiceDescription description = ServiceDescription.Read(stream); 
            ///// LOAD THE DOM ///////// 
            //--Initialize a service description importer. 
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); 
            importer.ProtocolName = "Soap12"; // Use SOAP 1.2. 
            importer.AddServiceDescription(description, null, null); 
            //--Generate a proxy client. importer.Style = ServiceDescriptionImportStyle.Client; 
            //--Generate properties to represent primitive values. 
            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; 
            //--Initialize a Code-DOM tree into which we will import the service. 
            CodeNamespace nmspace = new CodeNamespace(); 
            CodeCompileUnit unit1 = new CodeCompileUnit(); 
            unit1.Namespaces.Add(nmspace); 
            //--Import the service into the Code-DOM tree. This creates proxy code 
            //--that uses the service. 
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1); 
            if (warning == 0) //--If zero then we are good to go 
            { 
                //--Generate the proxy code  
                CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp"); 
                //--Compile the assembly proxy with the appropriate references 
                string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" }; 
                CompilerParameters parms = new CompilerParameters(assemblyReferences); 
                CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1); 
                //-Check For Errors 
                if (results.Errors.Count > 0) 
                { 
                    StringBuilder sb = new StringBuilder(); 
                    foreach (CompilerError oops in results.Errors) 
                    { 
                        sb.AppendLine("========Compiler error============"); 
                        sb.AppendLine(oops.ErrorText); 
                    } 
                    throw new System.ApplicationException("Compile Error Occured calling webservice. " + sb.ToString()); 
                } 
                //--Finally, Invoke the web service method  
                Type foundType = null; 
                Type[] types = results.CompiledAssembly.GetTypes(); 
                foreach (Type type in types) 
                { 
                    if (type.BaseType == typeof(System.Web.Services.Protocols.SoapHttpClientProtocol)) 
                    { 
                        Console.WriteLine(type.ToString()); 
                        foundType = type; 
                    } 
                } 

                object wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString()); 
                MethodInfo mi = wsvcClass.GetType().GetMethod(methodName); 
                return mi.Invoke(wsvcClass, args); 
            } 
            else 
            { 
                return null; 
            } 
        } 
    } 

I can't find anything static in what I do.

Any help is greatly appreciated.

Regards, Phani Kumar PV

解决方案

Let me try to explain the most probable reason for the problem to come in my approach.

When I invoked a method in the assembly called as "methodname" in the webservice I am trying to pass the parameters required for that as args[] to the function "CallWebService" This args[] when passed will be successfully working when I try to pass a normal parameters like primitive types including string.

But this is what I did when I tried to pass a custom object as a parameter.

Three things that are done in this.

  1. create an object of that type outside the CallWebService function (using reflection). when I did that way what happens is an instance of the customobject created with a temporary dll name internally.
  2. once I set the set the properties of the object and send it across to the CallWebService function as an object in the args array.
  3. I tired to create an instance of the webservice by creating the dynamic dll.

    object wsvcClass = results.CompiledAssembly.CreateInstance(foundType.ToString());

When I finally tried to invoke the method with the instance of the dynamic assembly created I tried to pass the customobject that is created at step 1,2 via args property.

at the time of invocation the CLR tries to see if the customobject that is passed as input and the method that is being invoked are from the same DLL.

which is obviously not from the way the implementation is done.

So following is the approach that should be used to overcome the problem I need to create the custom object assembly with the same assembly that I used to the create the webservice instance..

I implemented this approach completely and it worked out fine

MethodInfo m = type.GetMethod(methodName);
ParameterInfo[] pm = m.GetParameters();
object ob;
object[] y = new object[1];
foreach (ParameterInfo paraminfo in pm)
{
    ob = this.webServiceAssembly.CreateInstance(paraminfo.ParameterType.Name);

    //Some Junk Logic to get the set the values to the properties of the custom Object
    foreach (PropertyInfo propera in ob.GetType().GetProperties())
    {
        if (propera.Name == "AppGroupid")
        {
            propera.SetValue(ob, "SQL2005Tools", null);
        }
        if (propera.Name == "Appid")
        {
            propera.SetValue(ob, "%", null);
        }
    }
    y[0] = ob;
}

这篇关于类型'customObject'的对象不能转换为类型'customObject“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆