src/Converters/TypeConverterBase.cs

(开头部分) 5KB

这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Rapidity.Json.Converters
{
    internal abstract class TypeConverterBase : ITypeConverter
    {
        public Type Type { get; protected set; }

        public TypeConverterBase(Type type)
        {
            this.Type = type;
        }

        private Func<object> _createInstance;

        public virtual Func<object> CreateInstance
            => _createInstance = _createInstance ?? BuildCreateInstanceMethod(this.Type);

        /// <summary>
        /// 使用反射构造
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        protected virtual Func<object> BuildCreateInstanceMethod(Type type)
        {
            Func<object> func = () =>
            {
                //优先获取无参构造函数
                //查找参数最少的一个构造函数
                var constructors = type.GetConstructors().OrderBy(t => t.GetParameters().Length);
                if (constructors.Count() == 0)
                    return Activator.CreateInstance(type);
                var parameters = constructors.First().GetParameters();
                List<object> parametValues = new List<object>();
                foreach (var para in parameters)
                {
                    //有参构造函数使用默认值填充
                    var defaultValue = GetDefaultValue(para.ParameterType);
                    parametValues.Add(defaultValue);
                }
                return Activator.CreateInstance(type, parametValues.ToArray());
            };
            return func;
        }

        protected virtual Func<object> BuildCreateInstanceMethod2(Type type)
        {
            NewExpression newExp;
            //查找参数最少的一个构造函数
            var constructors = type.GetConstructors().OrderBy(t => t.GetParameters().Length);
            if (constructors.Count() == 0)
                newExp = Expression.New(type);
            else
            {
                var constructor = constructors.First();
                var parameters = constructor.GetParameters();
                List<Expression> parametExps = new List<Expression>();
后面还有 85 行代码,解锁后查看完整代码

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。