简体   繁体   English

C#如何使用反射从没有IConvertible的Type转换

[英]C# How to cast from Type without IConvertible using reflection

My returning value of the method CastTo is from the wrong type. 我的方法CastTo的返回值来自错误的类型。 The method CastTo has a returning parameter < T >. CastTo方法有一个返回参数<T>。

The commented line is what it does without using reflection 注释行是它在不使用反射的情况下所做的

            //FieldChoice ChoiceProduct = clientContext_temp.CastTo<FieldChoice>(field);
            Type FieldChoiceType = sharepointClient.GetType("Microsoft.SharePoint.Client.FieldChoice");
            object FieldChoice = Activator.CreateInstance(FieldChoiceType, sharepointClient, web.);
            MethodInfo castToMethodInfo = typeclientContext.GetMethod("CastTo");
            MethodInfo genericCastTo = castToMethodInfo.MakeGenericMethod(field.GetType());
            var ChoiceProduct = genericCastTo.Invoke(clientContext, new object[] { field });
            ChoiceProduct = Convert.ChangeType(ChoiceProduct, FieldChoiceType);

Choiceproduct is from the type Field but should be from the type FieldChoice. Choiceproduct来自Field类型,但应该来自FieldChoice类型。

The problem is, i can't create an instance of Fieldchoice before the method cause sharepoint just doesn't have a fittable constructor to allow creating it and i can't cast it to the Type with using Convert.changeType cause it doen't have a IConvertible implementation. 问题是,我无法在方法之前创建Fieldchoice的实例,因为sharepoint只是没有一个适合的构造函数来允许创建它,我无法使用Convert.changeType将它强制转换为Type,因为它不会有一个IConvertible实现。

Is there any other way i can cast my variable or change the return type of the method? 有没有其他方法可以转换我的变量或更改方法的返回类型?

我认为你的问题是你将field对象传递给genericCastTo而不是FieldChoice

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确定是否可以在没有IConvertible的情况下将对象强制转换为其他类型 - How toDetermine if an object can be cast to a different type, without IConvertible 在C#中使用Reflection进行转换 - Cast using Reflection in C# 使用反射c#将动态对象转换为类型 - Cast dynamic object to type using reflection c# 如何在C#中使用表示反射结果类型的变量进行转换.Invoke() - How in C# to cast using a variable representing a type for the result of reflection .Invoke() 无法将类型为“ Common.Date”的对象转换为类型为“ System.IConvertible C#” - Unable to cast object of type 'Common.Date' to type 'System.IConvertible C# C#反射转换为变量类型 - C# reflection cast to variable type C#无法将类型为“ TCSCapstone.frmInventory”的对象转换为类型为“ System.IConvertible”的对象 - C# Unable to cast object of type 'TCSCapstone.frmInventory' to type 'System.IConvertible' 如何在C#中使用Reflection强制转换对象运行时? - How to cast an object Run-time using Reflection in C#? 使用反射在 C# 中创建没有默认构造函数的类型实例 - Creating instance of type without default constructor in C# using reflection 无法将类型为“ System.Reflection.RuntimePropertyInfo”的对象转换为类型为“ System.IConvertible”的对象 - Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'System.IConvertible'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM