其他分享
首页 > 其他分享> > 强制转换为Spring.Collections.Set类型

强制转换为Spring.Collections.Set类型

作者:互联网

我使用Spring.NET来配置一些对象,并且编写了FactoryObject来使Quartz.NET日历的配置成为可以接受的方式.

它具有如下所示的属性,我们当然希望使用Spring.NET进行配置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz.Impl.Calendar;
using Spring.Objects.Factory;

namespace My.Package.TaskExecutorDemo
{

    /// <summary>
    /// TODO:
    /// </summary>
    public class WeeklyCalendarFactoryObject : WeeklyCalendar, IFactoryObject
    {
        private ISet<DayOfWeek> _daysOfWeek = new HashSet<DayOfWeek>();

        public ISet<DayOfWeek> DaysOfWeekExcluded
        {
            get { return _daysOfWeek; }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("DaysOfWeekExcluded");
                }
                _daysOfWeek = value;
            }
        }

        //Everything else ...
    }
}

它由以下对象定义配置.

<object id="weeklyCalendar" type="My.Package.TaskExecutorDemo.WeeklyCalendarFactoryObject, TaskExecutorDemo">
 <property name="DaysOfWeekExcluded">
   <set element-type="System.DayOfWeek, mscorlib">
     <value>Friday</value>
     <value>Saturday</value>
     <value>Sunday</value>
   </set>
 </property>
</object>

但是在启动时会引发以下异常:

Spring.Objects.Factory.ObjectCreationException: Error creating object with name ‘weeklyCalendar’ defined in ‘config [C:\Users\username\some\path\TaskExecutorDemo\bin\Debug\TaskExecutorDemo.exe.Config#spring/objects] line 7′ : Initialization of object failed : Unable to cast object of type System.Collections.Generic.HashSet`1[System.DayOfWeek]’ to type ‘Spring.Collections.ISet’.

System.InvalidCastException: Unable to cast object of type ‘System.Collections.Generic.HashSet`1[System.DayOfWeek]’ to type ‘Spring.Collections.ISet’.

但是我没有在代码的任何地方引用Spring.Collections.ISet.如何让Spring.NET正确配置ISet属性?

解决方法:

根据文档,ISet< T>不支持setting generic collection values;仅通用集合IDictionary< TKey,TValue>和IList< T>支持.尝试通过显式配置显式HashSet< T>.使用constructor taking an IEnumerable<T>.

标签:spring-net,c
来源: https://codeday.me/bug/20191030/1968740.html