Kentico RefreshSecurityParams函数中的代码会遇到错误Object must implement IConvertible.

 https://github.com/dotnet/runtime/blob/8377b0d938e1fecf0afda3d5a4f7f9bac3866bd5/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx#L2384

System.InvalidCastException: Object must implement IConvertible.
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at CMS.DataEngine.SimpleDataClass.SetData(Int32 columnIndex, Object value)
at CMS.DataEngine.SimpleDataClass.LoadData(IDataContainer data, Boolean loadNullValues)
at CMS.DataEngine.AbstractInfoBase`1.LoadData(LoadDataSettings settings)
at CMS.DataEngine.AbstractInfo`1.New(LoadDataSettings settings)
at CMS.DataEngine.AbstractInfo`1.NewObject(LoadDataSettings settings)
at CMS.DataEngine.ModuleManager.GetObject(LoadDataSettings settings)
at CMS.DataEngine.ModuleManager.GetObject(DataRow objectRow, String objectType, Boolean throwIfNotFound)
at CMS.DataEngine.InfoObjectCollection`1.CreateNewObject(DataRow dr)
at CMS.DataEngine.InfoObjectCollection`1.GetItemInternal(Int32 index)
at CMS.DataEngine.InfoObjectCollection`1.GetItem(Int32 index)
at CMS.DataEngine.InfoObjectCollection`1.get_InternalCount()
at CMS.DataEngine.InfoObjectCollection`1.<GetEnumeratorInternal>d__234.MoveNext()
at CMS.DataEngine.InfoObjectCollection`1.<GetEnumerator>d__233.MoveNext()
at UpgradeProcedure.RefreshSecurityParams() 

 private static void LoadCMSUser()
    {
        string str = "cms.user";
        InfoObjectCollection infos = new InfoObjectCollection(str);
        foreach (var info in infos)
        {
            Console.WriteLine();
        }
    }

这段代码,直接进行源码调试。

info.Generalized的类型是CMS.DataEngine.GeneralizedAbstractInfo`1[CMS.Membership.UserInfo]

info.Generalized.MainObject.GetType().ToString() 类型是CMS.Membership.UserInfo

问题出在转换数据上

Why doesn't Convert.ChangeType(string) work with DateTimeOffset, when it works with DateTime?

If you look at the documentation for the Convert.ChangeType method, you'll see the following note:

Exceptions
InvalidCastException
This conversion is not supported.
-or-
value is null and conversionType is a value type.
-or-
value does not implement the IConvertible interface.


Since we know that value is not null and that string implements the IConvertible interface, then the only reason left is the first one:

This conversion is not supported.


What we can do is first convert it to a DateTime, and then convert that to a DateTimeOffset. There is some documentation here that describes various methods to accomplish this, one of which is:

"You can also create a new DateTimeOffset value by assigning it a DateTime value"

So we can just do:

DateTimeOffset dateTimeOffset = (DateTime) Convert.ChangeType(dateString, typeof(DateTime));
原文地址:https://www.cnblogs.com/chucklu/p/14992039.html