示例#1
0
        public static void SetStockKey <TStockKey>(this IHasStockKey hasStockKey, TStockKey stockKey) where TStockKey : StockKeyBase
        {
            if (hasStockKey == null)
            {
                throw new ArgumentNullException(nameof(hasStockKey));
            }

            if (stockKey == null)
            {
                throw new ArgumentNullException(nameof(stockKey));
            }

            var entityProps = hasStockKey.GetType()
                              .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                              .ToArray();

            foreach (var keyProp in stockKey.GetType().GetProperties())
            {
                var entityProp = entityProps.SingleOrDefault(x => x.Name == keyProp.Name);
                if (entityProp == null)
                {
                    throw new InvalidOperationException($"未找到属性,类型【{hasStockKey.GetType()}】,名称【{keyProp.Name}】");
                }
                object value = keyProp.GetValue(stockKey);
                entityProp.SetValue(hasStockKey, value);
            }
        }
示例#2
0
        private static StockKeyBase GetStockKey(this IHasStockKey hasStockKey, Type stockKeyType)
        {
            if (hasStockKey == null)
            {
                throw new ArgumentNullException(nameof(hasStockKey));
            }

            if (stockKeyType == null)
            {
                throw new ArgumentNullException(nameof(stockKeyType));
            }

            if (typeof(StockKeyBase).IsAssignableFrom(stockKeyType) == false)
            {
                throw new ArgumentException("应为 StockKey 的子类", nameof(stockKeyType));
            }

            var entityProps = hasStockKey.GetType()
                              .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                              .ToArray();

            List <object> values = new List <object>();

            foreach (var keyParam in stockKeyType.GetConstructors()[0].GetParameters())
            {
                var entityProp = entityProps.SingleOrDefault(x => x.Name == keyParam.Name);
                if (entityProp == null)
                {
                    throw new InvalidOperationException($"未找到属性,类型【{hasStockKey.GetType()}】,名称【{keyParam.Name}】");
                }
                object value = entityProp.GetValue(hasStockKey);
                values.Add(value);
            }

            StockKeyBase stockKey = (StockKeyBase)Activator.CreateInstance(stockKeyType, values.ToArray());

            return(stockKey);
        }
示例#3
0
 public static TStockKey GetStockKey <TStockKey>(this IHasStockKey hasStockKey) where TStockKey : StockKeyBase
 {
     return((TStockKey)GetStockKey(hasStockKey, typeof(TStockKey)));
 }