首页 > 解决方案 > C# 如何使用反射从没有 IConvertible 的类型进行转换

问题描述

我的 CastTo 方法的返回值来自错误的类型。CastTo 方法有一个返回参数<T>。

注释行是它在不使用反射的情况下所做的

            //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 来自 Field 类型,但应该来自 FieldChoice 类型。

问题是,我无法在方法之前创建 Fieldchoice 的实例,因为 sharepoint 没有合适的构造函数来允许创建它,而且我无法使用 Convert.changeType 将其转换为 Type 因为它没有有一个 IConvertible 实现。

有没有其他方法可以转换我的变量或更改方法的返回类型?

标签: c#sharepointreflectioninvoke

解决方案


我认为您的问题是您将字段对象传递给 genericCastTo 而不是FieldChoice


推荐阅读