System.Type.GetGenericTypeDefinition()

Here are the examples of the csharp api System.Type.GetGenericTypeDefinition() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3110 Examples 7

19 View Source File : Protocol16Serializer.cs
License : MIT License
Project Creator : 0blu

private static Protocol16Type TypeCodeToProtocol16Type(Type type)
        {
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.Boolean:
                    return Protocol16Type.Boolean;
                case TypeCode.Byte:
                    return Protocol16Type.Byte;
                case TypeCode.Int16:
                    return Protocol16Type.Short;
                case TypeCode.Int32:
                    return Protocol16Type.Integer;
                case TypeCode.Int64:
                    return Protocol16Type.Long;
                case TypeCode.Single:
                    return Protocol16Type.Float;
                case TypeCode.Double:
                    return Protocol16Type.Double;
                case TypeCode.String:
                    return Protocol16Type.String;
            }

            if (type.IsArray)
            {
                var elementType = type.GetElementType();
                
                if (elementType == typeof(byte))
                {
                    return Protocol16Type.ByteArray;
                }

                if (elementType == typeof(string))
                {
                    return Protocol16Type.StringArray;
                }

                if (elementType == typeof(int))
                {
                    return Protocol16Type.IntegerArray;
                }

                if (elementType == typeof(object))
                {
                    return Protocol16Type.ObjectArray;
                }

                return Protocol16Type.Array;
            }

            if (type == typeof(Hashtable))
            {
                return Protocol16Type.Hashtable;
            }

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
            {
                return Protocol16Type.Dictionary;
            }

            if (type == typeof(EventData))
            {
                return Protocol16Type.EventData;
            }

            if (type == typeof(OperationRequest))
            {
                return Protocol16Type.OperationRequest;
            }

            if (type == typeof(OperationResponse))
            {
                return Protocol16Type.OperationResponse;
            }

            return Protocol16Type.Unknown;
        }

19 View Source File : CelesteNetUtils.cs
License : MIT License
Project Creator : 0x0ade

public static Type GetRequestType(this Type t) {
            Type[] interfaces = t.GetInterfaces();
            foreach (Type i in interfaces)
                if (i.IsConstructedGenericType && i.GetGenericTypeDefinition() == typeof(IDataRequestable<>))
                    return i.GetGenericArguments()[0];
            throw new Exception($"Invalid requested type: {t.FullName}");
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool IsImplementType(this Type serviceType, Type implementType)
    {
        //泛型
        if (serviceType.IsGenericType)
        {
            if (serviceType.IsInterface)
            {
                var interfaces = implementType.GetInterfaces();
                if (interfaces.Any(m => m.IsGenericType && m.GetGenericTypeDefinition() == serviceType))
                {
                    return true;
                }
            }
            else
            {
                if (implementType.BaseType != null && implementType.BaseType.IsGenericType && implementType.BaseType.GetGenericTypeDefinition() == serviceType)
                {
                    return true;
                }
            }
        }
        else
        {
            if (serviceType.IsInterface)
            {
                var interfaces = implementType.GetInterfaces();
                if (interfaces.Any(m => m == serviceType))
                    return true;
            }
            else
            {
                if (implementType.BaseType != null && implementType.BaseType == serviceType)
                    return true;
            }
        }
        return false;
    }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool IsSubclreplacedOfGeneric(this Type type, Type generic)
    {
        while (type != null && type != typeof(object))
        {
            var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
            if (generic == cur)
            {
                return true;
            }
            type = type.BaseType;
        }
        return false;
    }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool IsNullable(this Type type)
    {
        return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
    }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

internal static bool TypeIsCollection(Type t, out ConstructorInfo constructor, out Type itemType, out bool isImplGenerIList, out bool IsImplIList, out bool isImplGenerICollec, out bool isImplIReadOnlyList)
        {
            constructor = null;
            itemType = null;
            IsImplIList = false;
            isImplGenerIList = false;
            isImplGenerICollec = false;
            isImplIReadOnlyList = false;

            if (t.IsInterface)
            {
                if (t == typeof(IEnumerable) || t == typeof(ICollection) || t == typeof(IList))
                {
                    itemType = typeof(object);
                    if (t == typeof(IList))
                    {
                        IsImplIList = true;
                    }

                    return true;
                }

                if (t.IsGenericType)
                {
                    Type genericType = t.GetGenericTypeDefinition();
                    if (genericType == typeof(IEnumerable<>) || genericType == typeof(IList<>) || genericType == typeof(ICollection<>) || genericType == typeof(ISet<>) || genericType == typeof(IReadOnlyList<>) || genericType == typeof(IReadOnlyCollection<>))
                    {
                        if (genericType == typeof(IList<>))
                        {
                            isImplGenerIList = true;
                            isImplGenerICollec = true;
                        }
                        else if (genericType == typeof(ICollection<>) || genericType == typeof(ISet<>))
                        {
                            isImplGenerICollec = true;
                        }
                        else if (genericType == typeof(IReadOnlyList<>))
                        {
                            isImplIReadOnlyList = true;
                        }

                        itemType = t.GetGenericArguments()[0];
                        return true;
                    }
                }

                return false;
            }

            if (t.IsGenericType)
            {
                Type genericType = t.GetGenericTypeDefinition();
                if (genericType == typeof(List<>))
                {
                    itemType = t.GetGenericArguments()[0];
                    isImplGenerIList = true;
                    IsImplIList = true;
                    isImplGenerICollec = true;
                    isImplIReadOnlyList = true;
                    constructor = t.GetConstructor(new Type[] { typeof(int) });
                    return true;
                }
            }

            bool isImplGenerIEnumerable = false;
            bool isImplICollection = false;
            Type generIEnumerableItemType = null;
            Type generILisreplacedemType = null;
            Type generICollectionItemType = null;

            Type[] intserfaces = t.GetInterfaces();
            foreach (Type item in intserfaces)
            {
                if (item.IsGenericType)
                {
                    Type genericTypeDefinition = item.GetGenericTypeDefinition();

                    if (genericTypeDefinition == typeof(IEnumerable<>))
                    {
                        isImplGenerIEnumerable = true;
                        generIEnumerableItemType = item.GetGenericArguments()[0];
                    }
                    else if (genericTypeDefinition == typeof(ICollection<>))
                    {
                        isImplGenerICollec = true;
                        generICollectionItemType = item.GetGenericArguments()[0];
                    }
                    else if (genericTypeDefinition == typeof(IList<>))
                    {
                        isImplGenerIList = true;
                        generILisreplacedemType = item.GetGenericArguments()[0];
                    }
                }
                else if (item == typeof(ICollection))
                {
                    isImplICollection = true;
                }
                else if (item == typeof(IList))
                {
                    IsImplIList = true;
                }
            }

            if (isImplGenerIList)
            {
                if (TryGetConstructorInfo(t, generILisreplacedemType, true, out constructor))
                {
                    itemType = generILisreplacedemType;
                    return true;
                }
            }

            if (isImplGenerICollec)
            {
                if (TryGetConstructorInfo(t, generICollectionItemType, true, out constructor))
                {
                    itemType = generICollectionItemType;
                    return true;
                }
            }

            if (isImplGenerIEnumerable && isImplICollection)
            {
                if (TryGetConstructorInfo(t, generIEnumerableItemType, false, out constructor))
                {
                    itemType = generIEnumerableItemType;
                    return true;
                }
            }

            if (IsImplIList)
            {
                if (TryGetConstructorInfo(t, typeof(object), true, out constructor))
                {
                    itemType = typeof(object);
                    return true;
                }
            }

            if (isImplICollection)
            {
                if (TryGetConstructorInfo(t, typeof(object), false, out constructor))
                {
                    itemType = typeof(object);
                    return true;
                }
            }

            return false;
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

internal static bool TypeIsDictionary(Type t, out ConstructorInfo constructor, out bool typeIsGeneric, out Type genericTypeDefinition, out Type genericKeyType, out Type genericValueType)
        {
            constructor = null;
            typeIsGeneric = false;
            genericKeyType = null;
            genericValueType = null;
            genericTypeDefinition = null;

            Type genericType = null;
            bool hasIDictionaryGeneric = false;
            bool hasIDictionary = false;

            if (t.IsInterface)
            {
                if (t == typeof(IDictionary))
                {
                    return true;
                }

                if (t.IsGenericType)
                {
                    genericTypeDefinition = t.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(IDictionary<,>) || genericTypeDefinition == typeof(IReadOnlyDictionary<,>))
                    {
                        Type[] args = t.GetGenericArguments();
                        typeIsGeneric = true;
                        genericType = t;
                        genericKeyType = args[0];
                        genericValueType = args[1];
                        return true;
                    }
                }
                return false;
            }

            if (t.IsGenericType)
            {
                genericTypeDefinition = t.GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(Dictionary<,>) ||
                    genericTypeDefinition == typeof(SortedList<,>))
                {
                    constructor = t.GetAppointTypeCtor(typeof(int));
                    typeIsGeneric = true;
                    Type[] args = t.GetGenericArguments();
                    genericKeyType = args[0];
                    genericValueType = args[1];
                    return true;
                }
            }

            IEnumerable<Type> intserfaces = t.GetInterfaces();
            foreach (Type item in intserfaces)
            {
                if (item.IsGenericType)
                {
                    genericTypeDefinition = item.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(IDictionary<,>) ||
                        genericTypeDefinition == typeof(IReadOnlyDictionary<,>))
                    {
                        genericType = item;
                        Type[] args = item.GetGenericArguments();
                        genericKeyType = args[0];
                        genericValueType = args[1];
                        hasIDictionaryGeneric = true;
                        break;
                    }
                }
                else if (item == typeof(IDictionary))
                {
                    hasIDictionary = true;
                }
            }

            if (hasIDictionaryGeneric)
            {
                typeIsGeneric = true;

                //clreplaced <T>:IDictionary<int,int>
                //     ctor( ReadOnlyDic<,> )
                //     ctor( Dictionary<,>  )
                if (TryGetConstructorInfo(t, genericKeyType, genericValueType, true, out constructor))
                {
                    return true;
                }
            }
            else if (hasIDictionary)
            {
                constructor = t.GetDefaultNoArgCtorOrAppointTypeCtor(typeof(IDictionary));
                if (constructor != null)
                {
                    return true;
                }
            }

            return false;
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type elementType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineCollectionFormatterType(type, elementType);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);

            if (type.IsGenericType == false)
            {
                DEBUG.replacedert(type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection));
                //itemType is Object, Array2
                if (type == typeof(IList))
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(object)));

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                Type genericTypeDefine = type.GetGenericTypeDefinition();
                DEBUG.replacedert(genericTypeDefine == typeof(IEnumerable<>) || genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(ICollection<>) || genericTypeDefine == typeof(ISet<>) || genericTypeDefine == typeof(IReadOnlyList<>) || genericTypeDefine == typeof(IReadOnlyCollection<>));

                if (Array1FormatterHelper.IsArray1Type(elementType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.DeserializeSetPrefix + elementType.Name, BindingFlags.Public | BindingFlags.Static));
                    }
                    else
                    {
                        Type listFormatterType = Array1ResolverGetFormatterHelper.GetListFormatterType(elementType);
                        FieldInfo field = listFormatterType.GetField(nameof(DateTimeListFormatter.Instance), BindingFlags.Static | BindingFlags.Public);
                        MethodInfo method = listFormatterType.GetMethod(nameof(DateTimeListFormatter.Deserialize));
                        TypeBuildHelper.CallOneStaticFieldMethodInDeserialize(deserializeMethod, field, method);
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));
                }
                else
                {
                    if (genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(IReadOnlyList<>))
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeSet), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                }
            }

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToProxy(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            var isResult = false;

            if (isAsync)
            {
                sb.AppendLine($"            await _context.BeforeAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.Before(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isAsync)
            {
                sb.AppendLine($"            await _context.AfterAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.After(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

19 View Source File : TccMaster.cs
License : MIT License
Project Creator : 2881099

TccMaster<TDBKey> Then(Type tccUnitType, object state)
        {
            if (tccUnitType == null) throw new ArgumentNullException(nameof(tccUnitType));
            var unitTypeBase = typeof(TccUnit<>);
            if (state == null && tccUnitType.BaseType.GetGenericTypeDefinition() == typeof(TccUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(tccUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(tccUnitType) == false) throw new ArgumentException($"{tccUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = tccUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{tccUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(tccUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{tccUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ITccUnit;
            (unit as ITccUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new TccUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = TccUnitStage.Try,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = tccUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099

public static string ToMethod(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public static ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            var isResult = false;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

19 View Source File : SagaMaster.cs
License : MIT License
Project Creator : 2881099

SagaMaster<TDBKey> Then(Type sagaUnitType, object state)
        {
            if (sagaUnitType == null) throw new ArgumentNullException(nameof(sagaUnitType));
            var unitTypeBase = typeof(SagaUnit<>);
            if (state == null && sagaUnitType.BaseType.GetGenericTypeDefinition() == typeof(SagaUnit<>)) unitTypeBase = unitTypeBase.MakeGenericType(sagaUnitType.BaseType.GetGenericArguments()[0]);
            else unitTypeBase = unitTypeBase.MakeGenericType(state.GetType());
            if (unitTypeBase.IsreplacedignableFrom(sagaUnitType) == false) throw new ArgumentException($"{sagaUnitType.DisplayCsharp(false)} 必须继承 {unitTypeBase.DisplayCsharp(false)}");
            var unitCtors = sagaUnitType.GetConstructors();
            if (unitCtors.Length != 1 && unitCtors[0].GetParameters().Length > 0) throw new ArgumentException($"{sagaUnitType.FullName} 不能使用构造函数");

            var unitTypeConved = Type.GetType(sagaUnitType.replacedemblyQualifiedName);
            if (unitTypeConved == null) throw new ArgumentException($"{sagaUnitType.FullName} 无效");
            var unit = unitTypeConved.CreateInstanceGetDefaultValue() as ISagaUnit;
            (unit as ISagaUnitSetter)?.SetState(state);
            _thenUnits.Add(unit);
            _thenUnitInfos.Add(new SagaUnitInfo
            {
                Description = unitTypeConved.GetDescription(),
                Index = _thenUnitInfos.Count + 1,
                Stage = SagaUnitStage.Commit,
                State = state == null ? null : Newtonsoft.Json.JsonConvert.SerializeObject(state),
                StateTypeName = state?.GetType().replacedemblyQualifiedName,
                Tid = _tid,
                TypeName = sagaUnitType.replacedemblyQualifiedName,
            });
            return this;
        }

19 View Source File : ValueMember.cs
License : MIT License
Project Creator : 404Lcc

internal bool ResolveMapTypes(out Type dictionaryType, out Type keyType, out Type valueType)
        {
            dictionaryType = keyType = valueType = null;
            try
            {
#if WINRT || COREFX || PROFILE259
				var info = memberType.GetTypeInfo();
#else
                var info = memberType;
#endif
			MethodInfo b, a, ar, f;
            if(ImmutableCollectionDecorator.IdentifyImmutable(model, MemberType, out b, out a, out ar, out f))
                {
                    return false;
                }
                if (info.IsInterface && info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
                {
#if PROFILE259
					var typeArgs = memberType.GetGenericTypeDefinition().GenericTypeArguments;
#else
					var typeArgs = memberType.GetGenericArguments();
#endif
					if (IsValidMapKeyType(typeArgs[0]))
                    {
                        keyType = typeArgs[0];
                        valueType = typeArgs[1];
                        dictionaryType = memberType;
                    }
                    return false;
                }
#if PROFILE259
				foreach (var iType in memberType.GetTypeInfo().ImplementedInterfaces)
#else
				foreach (var iType in memberType.GetInterfaces())
#endif
				{
#if WINRT || COREFX || PROFILE259
					info = iType.GetTypeInfo();
#else
                    info = iType;
#endif
                    if (info.IsGenericType && info.GetGenericTypeDefinition() == typeof(IDictionary<,>))
                    {
                        if (dictionaryType != null) throw new InvalidOperationException("Multiple dictionary interfaces implemented by type: " + memberType.FullName);
#if PROFILE259
						var typeArgs = iType.GetGenericTypeDefinition().GenericTypeArguments;
#else
						var typeArgs = iType.GetGenericArguments();
#endif
						if (IsValidMapKeyType(typeArgs[0]))
                        {
                            keyType = typeArgs[0];
                            valueType = typeArgs[1];
                            dictionaryType = memberType;
                        }
                    }
                }
                if (dictionaryType == null) return false;

                // (note we checked the key type already)
                // not a map if value is repeated
                Type itemType = null, defaultType = null;
                model.ResolveListTypes(valueType, ref itemType, ref defaultType);
                if (itemType != null) return false;

                return dictionaryType != null;
            }
            catch
            {
                // if it isn't a good fit; don't use "map"
                return false;
            }
        }

19 View Source File : ReflectionExtensions.cs
License : Apache License 2.0
Project Creator : 42skillz

public static bool IsEnumerable(this Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 52ABP

public static bool IsNullableType(this Type type)
        {
            return (type != null) && type.IsGenericType && (type.GetGenericTypeDefinition() == typeof (Nullable<>));
        }

19 View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab

internal static object ParseValue(Type type, string json) {
            if (type == typeof(string)) {
                if (json.Length <= 2)
                    return string.Empty;
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
            }
            if (type == typeof(int)) {
                int result;
                int.TryParse(json, out result);
                return result;
            }
            if (type == typeof(float)) {
                float result;
                float.TryParse(json, out result);
                return result;
            }
            if (type == typeof(double)) {
                double result;
                double.TryParse(json, out result);
                return result;
            }
            if (type == typeof(bool)) {
                return json.ToLower() == "true";
            }
            if (json == "null") {
                return null;
            }
            if (type.IsArray) {
                Type arrayType = type.GetElementType();
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                Array newArray = Array.CreateInstance(arrayType, elems.Count);
                for (int i = 0; i < elems.Count; i++)
                    newArray.SetValue(ParseValue(arrayType, elems[i]), i);
                splitArrayPool.Push(elems);
                return newArray;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
                Type listType = type.GetGenericArguments()[0];
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
                for (int i = 0; i < elems.Count; i++)
                    list.Add(ParseValue(listType, elems[i]));
                splitArrayPool.Push(elems);
                return list;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
                Type keyType, valueType;
                {
                    Type[] args = type.GetGenericArguments();
                    keyType = args[0];
                    valueType = args[1];
                }

                //Refuse to parse dictionary keys that aren't of type string
                if (keyType != typeof(string))
                    return null;
                //Must be a valid dictionary element
                if (json[0] != '{' || json[json.Length - 1] != '}')
                    return null;
                //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;

                var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
                for (int i = 0; i < elems.Count; i += 2) {
                    if (elems[i].Length <= 2)
                        continue;
                    string keyValue = elems[i].Substring(1, elems[i].Length - 2);
                    object val = ParseValue(valueType, elems[i + 1]);
                    dictionary.Add(keyValue, val);
                }
                return dictionary;
            }
            if (type == typeof(object)) {
                return ParseAnonymousValue(json);
            }
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                return ParseObject(type, json);
            }

            return null;
        }

19 View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71

private bool TryGetGenericEnumerableArgument (out Type argument)
		{
			argument = null;

			foreach (var iface in Enumerable.Type.GetTypeInfo().ImplementedInterfaces)
            {
				if (iface.GenericTypeArguments.Length == 0)
					continue;

				var definition = iface.GetGenericTypeDefinition();
				if (definition != typeof(IEnumerable<>))
					continue;

				argument = iface.GenericTypeArguments[0];

				if (Variable.Type.GetTypeInfo().IsreplacedignableFrom(argument.GetTypeInfo()))
					return true;
			}

			return false;
		}

19 View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71

public static IEnumerable<T> FindAttributesOfInterface<T>(this ImmutableArray<AttributeData> attributes)
        {
            Type interfType = typeof(T);

            if (!interfType.GetTypeInfo().IsInterface)
                throw new ArgumentException("Expected an interface.");

            string metadataName = interfType.IsConstructedGenericType
                ? interfType.GetGenericTypeDefinition().FullName
                : interfType.FullName;

            for (int i = 0; i < attributes.Length; i++)
            {
                AttributeData data = attributes[i];
                ImmutableArray<INamedTypeSymbol> interfaces = data.AttributeClreplaced.AllInterfaces;

                for (int o = 0; o < interfaces.Length; o++)
                {
                    INamedTypeSymbol interf = interfaces[o];

                    if (interf.MetadataName != metadataName)
                        continue;

                    // We got this far, so we have a valid attribute; construct it.
                    yield return data.Construct<T>();
                    break;
                }
            }
        }

19 View Source File : AwaitExpression.cs
License : MIT License
Project Creator : 71

public static AwaitExpression Await(Expression task, MethodInfo method)
        {
            Requires.NotNull(task, nameof(task));

            if (method == null)
                return Await(task);

            if (method.ReturnType != typeof(TaskAwaiter)
                && method.ReturnType.GetGenericTypeDefinition() != typeof(TaskAwaiter<>))
                throw new ArgumentException("Method does not return a TaskAwaiter.", nameof(method));

            ParameterInfo[] parameters = method.GetParameters();

            if (method.IsStatic)
            {
                if (parameters.Length != 1 || parameters[0].ParameterType.GetTypeInfo().IsreplacedignableFrom(task.Type.GetTypeInfo()))
                    throw new ArgumentException("Invalid method signature.", nameof(method));
            }
            else
            {
                if (parameters.Length != 0)
                    throw new ArgumentException("Invalid method signature.", nameof(method));
            }

            return new AwaitExpression(task, method);
        }

19 View Source File : CometaryExtensions.cs
License : MIT License
Project Creator : 71

public static IEnumerable<T> FindAttributesOfType<T>(this ImmutableArray<AttributeData> attributes, bool allowInherited = true)
        {
            Type type = typeof(T);

            if (type.GetTypeInfo().IsInterface)
                throw new ArgumentException("Expected a type.");

            string metadataName = type.IsConstructedGenericType
                ? type.GetGenericTypeDefinition().Name
                : type.Name;

            for (int i = 0; i < attributes.Length; i++)
            {
                AttributeData data = attributes[i];
                ITypeSymbol typeSymbol = data.AttributeClreplaced;

                if (!allowInherited && typeSymbol.MetadataName == metadataName)
                {
                    yield return data.Construct<T>();
                }
                else if (allowInherited)
                {
                    while (typeSymbol != null)
                    {
                        if (typeSymbol.MetadataName == metadataName)
                        {
                            yield return data.Construct<T>();
                            break;
                        }

                        typeSymbol = typeSymbol.BaseType;
                    }
                }
            }
        }

19 View Source File : AwaitExpression.cs
License : MIT License
Project Creator : 71

public static AwaitExpression Await(Expression task)
        {
            Requires.NotNull(task, nameof(task));

            MethodInfo method = task.Type.GetRuntimeMethods()
                                    .FirstOrDefault(x => x.ReturnType == typeof(TaskAwaiter) ||
                                                         x.ReturnType.IsConstructedGenericType &&
                                                         x.ReturnType.GetGenericTypeDefinition() == typeof(TaskAwaiter<>));

            if (method == null)
                throw new ArgumentException("The given argument must be awaitable.", nameof(task));

            return new AwaitExpression(task, method);
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WrapVector(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Vector<>));
            var vectorT = valueType.GetGenericArguments().First();

            _writeVectorTMethod.MakeGenericMethod(vectorT).Invoke(this, new object[] { value, context });
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WrapDictionary(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Amf3Dictionary<,>));
            var tKey = valueType.GetGenericArguments().First();
            var tValue = valueType.GetGenericArguments().Last();

            _writeDictionaryTMethod.MakeGenericMethod(tKey, tValue).Invoke(this, new object[] { value, context });
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

public void WriteValueBytes(object value, SerializationContext context)
        {
            if (value == null)
            {
                WriteBytes((object)null, context);
                return;
            }
            var valueType = value.GetType();
            if (_writeHandlers.TryGetValue(valueType, out var handler))
            {
                handler(value, context);
            }
            else
            {
                if (valueType.IsGenericType)
                {
                    var genericDefination = valueType.GetGenericTypeDefinition();

                    if (genericDefination != typeof(Vector<>) && genericDefination != typeof(Amf3Dictionary<,>))
                    {
                        throw new NotSupportedException();
                    }

                    if (_writeHandlers.TryGetValue(genericDefination, out handler))
                    {
                        handler(value, context);
                    }
                }
                else
                {
                    WriteBytes(value, context);
                }
            }


        }

19 View Source File : RtmpSession.cs
License : MIT License
Project Creator : a1q123456

internal void CommandHandler(RtmpController controller, CommandMessage command)
        {
            MethodInfo method = null;
            object[] arguments = null;
            try
            {
                _rpcService.PrepareMethod(controller, command, out method, out arguments);
                var result = method.Invoke(controller, arguments);
                if (result != null)
                {
                    var resType = method.ReturnType;
                    if (resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(Task<>))
                    {
                        var tsk = result as Task;
                        tsk.ContinueWith(t =>
                        {
                            var taskResult = resType.GetProperty("Result").GetValue(result);
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = true;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = taskResult;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnRanToCompletion);
                        tsk.ContinueWith(t =>
                        {
                            var exception = tsk.Exception;
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = false;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = exception.Message;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                    else if (resType == typeof(Task))
                    {
                        var tsk = result as Task;
                        tsk.ContinueWith(t =>
                        {
                            var exception = tsk.Exception;
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = false;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = exception.Message;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                    else if (resType != typeof(void))
                    {
                        var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                        retCommand.IsSuccess = true;
                        retCommand.TranscationID = command.TranscationID;
                        retCommand.CommandObject = null;
                        retCommand.ReturnValue = result;
                        _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                    }
                }
            }
            catch (Exception e)
            {
                var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                retCommand.IsSuccess = false;
                retCommand.TranscationID = command.TranscationID;
                retCommand.CommandObject = null;
                retCommand.ReturnValue = e.Message;
                _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                return;
            }
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : a34546

public static bool HasImplementedRawGeneric(this Type type, Type generic)
        {
            if (type == null) throw new ArgumentNullException(nameof(type));
            if (generic == null) throw new ArgumentNullException(nameof(generic));
            var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
            if (isTheRawGenericType) return true;
            while (type != null && type != typeof(object))
            {
                isTheRawGenericType = IsTheRawGenericType(type);
                if (isTheRawGenericType) return true;
                type = type.BaseType;
            }
            return false;

            bool IsTheRawGenericType(Type test)
                => generic == (test.IsGenericType ? test.GetGenericTypeDefinition() : test);
        }

19 View Source File : Database.cs
License : Apache License 2.0
Project Creator : aadreja

internal bool IsNullableType(Type type)
        {
            if (!type.IsGenericType)
            {
                return false;
            }
            if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

private static Type GetTypeOfDynamicProperty(PropertyInfo property, object dynamicObject)
        {
            //dynamic property will always return System.Object as property type. Get Type from the value

            Type type = property.PropertyType;

            if (type == typeof(object))
                type = property.GetValue(dynamicObject)?.GetType() ?? typeof(object);
            else
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(property.PropertyType);
                else
                    type = property.PropertyType;
            }

            return type;
        }

19 View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj

internal static VxFormGroup CreateFromModel(object modelInstance, VxFormLayoutOptions options)
        {
            var typeToCheck = modelInstance.GetType();
            // check for generics
            if (typeToCheck.IsGenericType)
                typeToCheck = typeToCheck.GetGenericTypeDefinition();

            var allProperties = VxHelpers.GetModelProperties(typeToCheck);

            var rootGroup = VxFormGroup.Create();

            foreach (var prop in allProperties)
            {
                VxFormGroup.Add(prop.Name, rootGroup, modelInstance, options);
            }

            return rootGroup;
        }

19 View Source File : VxHelpers.cs
License : MIT License
Project Creator : Aaltuj

public static bool IsTypeDerivedFromGenericType(Type typeToCheck, Type genericType)
        {
            if (typeToCheck == typeof(object))
            {
                return false;
            }
            else if (typeToCheck == null)
            {
                return false;
            }
            else if (typeToCheck.IsGenericType && typeToCheck.GetGenericTypeDefinition() == genericType)
            {
                return true;
            }
            else
            {
                return IsTypeDerivedFromGenericType(typeToCheck.BaseType, genericType);
            }
        }

19 View Source File : GenericInterface.cs
License : MIT License
Project Creator : Accelerider

public static IGenericInterface AsGenericInterface(this object @this, Type type)
        {
            var interfaceType = (
                    from @interface in @this.GetType().GetInterfaces()
                    where @interface.IsGenericType
                    let definition = @interface.GetGenericTypeDefinition()
                    where definition == type
                    select @interface
                )
                .SingleOrDefault();

            return interfaceType != null
                ? new GenericInterfaceImpl(@this, interfaceType)
                : null;
        }

19 View Source File : TypeExtensionMethods.cs
License : MIT License
Project Creator : actions

public static bool IsDictionary(this Type type)
        {
            if (typeof(IDictionary).GetTypeInfo().IsreplacedignableFrom(type.GetTypeInfo()))
            {
                //non-generic dictionary
                return true;
            }
            else if (type.GetTypeInfo().IsGenericType &&
                     type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
            {
                //generic dictionary interface
                return true;
            }
            else if (type.GetTypeInfo().ImplementedInterfaces.Any(
                        i => i.GetTypeInfo().IsGenericType &&
                             i.GetGenericTypeDefinition() == typeof(IDictionary<,>)))
            {
                //implements generic dictionary
                return true;
            }

            return false;
        }

19 View Source File : TypeExtensionMethods.cs
License : MIT License
Project Creator : actions

public static bool IsList(this Type type)
        {
            if (typeof(IList).GetTypeInfo().IsreplacedignableFrom(type.GetTypeInfo()))
            {
                //non-generic list
                return true;
            }
            else if (type.GetTypeInfo().IsGenericType &&
                     type.GetGenericTypeDefinition() == typeof(IList<>))
            {
                //generic list interface
                return true;
            }
            else if (type.GetTypeInfo().ImplementedInterfaces.Any(
                        i => i.GetTypeInfo().IsGenericType &&
                             i.GetGenericTypeDefinition() == typeof(IList<>)))
            {
                //implements generic list
                return true;
            }

            return false;
        }

19 View Source File : TypeExtensionMethods.cs
License : MIT License
Project Creator : actions

public static bool IsOfType(this Type type, Type t)
        {
            if (t.GetTypeInfo().IsreplacedignableFrom(type.GetTypeInfo()))
            {
                return true;
            }
            else if (type.GetTypeInfo().IsGenericType &&
                     type.GetGenericTypeDefinition() == t)
            {
                //generic type
                return true;
            }
            else if (type.GetTypeInfo().ImplementedInterfaces.Any(
                        i => i.GetTypeInfo().IsGenericType &&
                             i.GetGenericTypeDefinition() == t))
            {
                //implements generic type
                return true;
            }

            return false;
        }

19 View Source File : LaminarValueFactory.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private ITypeDefinitionProvider GetProvider(object value)
        {
            if (value is ITypeDefinitionProvider typeDefinitionProvider)
            {
                return typeDefinitionProvider;
            }

            if (value.GetType().IsGenericType && value.GetType().GetInterfaces().Where(x => x.IsGenericType).Select(x => x.GetGenericTypeDefinition()).Contains(typeof(ITypeDefinitionConstructor<>)))
            {
                value = ((dynamic)value).Construct();
            }

            if (value is ITypeDefinition typeDefinition)
            {
                IManualTypeDefinitionProvider manager = _factory.GetImplementation<IManualTypeDefinitionProvider>();
                manager.RegisterTypeDefinition(typeDefinition);
                return manager;
            }

            if (value is Type type)
            {
                IRigidTypeDefinitionManager manager = _factory.GetImplementation<IRigidTypeDefinitionManager>();
                manager.SetType(type);
                return manager;
            }

            IRigidTypeDefinitionManager rigidTypeDefinitionManager = _factory.GetImplementation<IRigidTypeDefinitionManager>();
            rigidTypeDefinitionManager.SetTypeDefinition(value, null, null);
            return rigidTypeDefinitionManager;
        }

19 View Source File : Serializer.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public object TryDeserializeObject(object serialized, Type requestedType, object deserializationContext)
        {
            if (requestedType is not null)
            {
                if (requestedType.IsEnum)
                {
                    return Enum.ToObject(requestedType, serialized);
                }
            }

            Type deserializedType = serialized.GetType().GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ISerializedObject<>)).FirstOrDefault()?.GetGenericArguments()[0];
            if (deserializedType is not null && Serializers.TryGetValue(deserializedType, out object serializer))
            {
                return typeof(IObjectSerializer<>).MakeGenericType(deserializedType).GetMethod(nameof(IObjectSerializer<object>.DeSerialize)).Invoke(serializer, new object[] { serialized, this, deserializationContext });
            }


            if (requestedType is not null)
            {
            }

            return serialized;
        }

19 View Source File : Serializer.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private void InitializeDictionaries()
        {
            foreach (Type type in typeof(Serializer).replacedembly.GetTypes())
            {
                Type serializerType = type.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IObjectSerializer<>)).FirstOrDefault();
                if (serializerType is not null)
                {
                    object serializer = _factory.CreateInstance(type);
                    Type genericParameter = serializerType.GetGenericArguments().FirstOrDefault();
                    Serializers.Add(genericParameter, serializer);
                }
            }
        }

19 View Source File : ObjectFactory.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private bool TryGetImplementation(Type inputType, out Type outputType)
        {
            if (_interfaceImplementations.TryGetValue(inputType, out Type implementation))
            {
                outputType = implementation;
                return true;
            }

            if (inputType.IsGenericType && _interfaceImplementations.TryGetValue(inputType.GetGenericTypeDefinition(), out Type implementationType))
            {
                outputType = implementationType.MakeGenericType(inputType.GetGenericArguments());
                return true;
            }

            outputType = default;
            return false;
        }

19 View Source File : ObjectFactory.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private void RegisterImplementationUnsafe(Type interfaceType, Type implementationType)
        {
            Type[] interfaces = implementationType.GetInterfaces();
            if (!(implementationType.GetInterfaces().Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == interfaceType)) && implementationType.IsClreplaced))
            {
                throw new ArgumentException($"Type {implementationType} is not a clreplaced that inherits from {interfaceType}");
            }

            _interfaceImplementations.Add(interfaceType, implementationType);
        }

19 View Source File : MessageHandlerContainer.cs
License : MIT License
Project Creator : AdemCatamak

private static List<Type> GetPayloadTypes(Type messageHandlerType)
        {
            List<Type> payloadTypes = new List<Type>();
            foreach (Type interfaceType in messageHandlerType.GetInterfaces())
            {
                if (interfaceType.IsGenericType
                 && interfaceType.GetGenericTypeDefinition() == typeof(IMessageHandler<>))
                {
                    payloadTypes.Add(interfaceType.GetGenericArguments()[0]);
                }
            }

            return payloadTypes.Distinct().ToList();
        }

19 View Source File : ObjectShredder.cs
License : MIT License
Project Creator : Adoxio

public DataTable ExtendTable(DataTable table, Type type)
		{
			// Extend the table schema if the input table was null or if the value 
			// in the sequence is derived from type T.            
			foreach (FieldInfo f in type.GetFields())
			{
				if (!_ordinalMap.ContainsKey(f.Name))
				{
					var ft = f.FieldType;

					if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						ft = Nullable.GetUnderlyingType(ft);
					}

					// Add the field as a column in the table if it doesn't exist
					// already.
					DataColumn dc = table.Columns.Contains(f.Name)
						? table.Columns[f.Name]
						: table.Columns.Add(f.Name, ft);

					// Add the field to the ordinal map.
					_ordinalMap.Add(f.Name, dc.Ordinal);
				}
			}
			foreach (PropertyInfo p in type.GetProperties())
			{
				if (!_ordinalMap.ContainsKey(p.Name))
				{
					var pt = p.PropertyType;

					if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						pt = Nullable.GetUnderlyingType(pt);
					}

					// Add the property as a column in the table if it doesn't exist
					// already.
					DataColumn dc = table.Columns.Contains(p.Name)
						? table.Columns[p.Name]
						: table.Columns.Add(p.Name, pt);

					// Add the property to the ordinal map.
					_ordinalMap.Add(p.Name, dc.Ordinal);
				}
			}

			// Return the table.
			return table;
		}

19 View Source File : OrganizationServiceContextInfo.cs
License : MIT License
Project Creator : Adoxio

private IDictionary<string, EnreplacedySetInfo> LoadEnreplacedySets(Func<PropertyInfo, EnreplacedyInfo, string> keySelector)
		{
			var dataContextPublicProperties = ContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);

			var enreplacedySetTypes =
				from property in dataContextPublicProperties
				let propertyType = property.PropertyType
				where propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(IQueryable<>)
				let enreplacedyType = propertyType.GetGenericArguments().First()
				select new EnreplacedySetInfo(property, new EnreplacedyInfo(enreplacedyType));

			var enreplacedySets = new Dictionary<string, EnreplacedySetInfo>();

			foreach (var type in enreplacedySetTypes)
			{
				var key = keySelector(type.Property, type.Enreplacedy);

				if (!string.IsNullOrEmpty(key))
				{
					enreplacedySets.Add(key, type);
				}
			}

			return enreplacedySets;
		}

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : Adoxio

public static IEnumerable<PropertyInfo> GetEnreplacedySetProperties(this Type crmDataContextType)
		{
			crmDataContextType.ThrowOnNull("crmDataContextType");

			var dataContextPublicProperties = crmDataContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);

			return dataContextPublicProperties.Where(property =>
			{
				var propertyType = property.PropertyType;

				if (!propertyType.IsGenericType)
				{
					return false;
				}

				var genericDefinition = propertyType.GetGenericTypeDefinition();

				return genericDefinition == typeof(IQueryable<>);
			});
		}

19 View Source File : MethodReferenceExtensions.cs
License : MIT License
Project Creator : AElfProject

public static bool IsMethodReference(this Type type)
        {
            if (type.IsConstructedGenericType)
            {
                return type.GetGenericTypeDefinition() == typeof(MethodReference<,>);
            }

            return type == typeof(MethodReference<,>);
        }

19 View Source File : WebWebAppAElfModule.cs
License : MIT License
Project Creator : AElfProject

public override bool CanWriteResult(OutputFormatterCanWriteContext context)
        {
            MediaTypeHeaderValue.TryParse(context.ContentType, out var parsedContentType);

            if (context.Object == null || parsedContentType == null || !parsedContentType.IsSubsetOf(protoMediaType))
            {
                return false;
            }

            // Check whether the given object is a proto-generated object
            return context.ObjectType.GetTypeInfo()
                .ImplementedInterfaces
                .Where(i => i.GetTypeInfo().IsGenericType)
                .Any(i => i.GetGenericTypeDefinition() == typeof(IMessage<>));
        }

19 View Source File : PredicateConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private string Convert(MethodCallExpression expression)
        {
            if (expression.Method.DeclaringType == null)
            {
                throw new ArgumentException("��֧�ֲ����ķ���(��֧�����Եķ���)");
            }
            if (expression.Method.DeclaringType == typeof(string))
            {
                switch (expression.Method.Name)
                {
                    case "ToUpper":
                        return $"upper({ConvertExpression(expression.Object)})";
                    case "Equals":
                        return $"({ConvertExpression(expression.Object)} = {GetArguments(expression)})";
                    case "Contains":
                        return
                            $"({ConvertExpression(expression.Object)} Like '%'+{GetArguments(expression)}+'%')";
                    case "ToLower":
                        return $"lower({ConvertExpression(expression.Object)})";
                    case "Trim":
                        return $"trim({ConvertExpression(expression.Object)})";
                    case "TrimStart":
                        return $"ltrim({ConvertExpression(expression.Object)})";
                    case "TrimEnd":
                        return $"rtrim({ConvertExpression(expression.Object)})";
                    case "Replace":
                        return $"replace({ConvertExpression(expression.Object)},{GetArguments(expression)})";
                }
                throw new ArgumentException("��֧�ַ���");
            }
            if (expression.Method.DeclaringType.IsValueType && expression.Method.Name == "Equals")
                return $"({ConvertExpression(expression.Object)} = {GetArguments(expression)})";
            if (expression.Method.DeclaringType == typeof(Math))
            {
                switch (expression.Method.Name)
                {
                    case "Abs":
                        return $"abs({GetArguments(expression)})";
                }
            }
            if (expression.Method.DeclaringType == typeof(Enum))
            {
                switch (expression.Method.Name)
                {
                    case "HasFlag":
                        return string.Format("({0} & {1}) = {1}", ConvertExpression(expression.Object), GetArguments(expression));
                }
            }
            if (expression.Method.DeclaringType.IsGenericTypeDefinition && expression.Method.DeclaringType.GetGenericTypeDefinition() == typeof(List<>))
            {
                switch (expression.Method.Name)
                {
                    case "Contains":
                        return $"{GetArguments(expression)} in ({ConvertExpression(expression.Object)})";
                }
            }
            var name = _condition.AddParameter(GetValue(expression));
            return $"@{name}";
        }

19 View Source File : PredicateConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private string Convert(MethodCallExpression expression)
        {
            if (expression.Method.DeclaringType == null)
            {
                throw new ArgumentException("��֧�ֲ����ķ���(��֧�����Եķ���)");
            }
            if (expression.Method.Name == "Equals")
            {
                var left = ConvertExpression(expression.Object);
                var right = GetArguments(expression);
                if ((left == null || string.Equals(left, "null", StringComparison.OrdinalIgnoreCase) &&
                     (right == null || string.Equals(right, "null", StringComparison.OrdinalIgnoreCase))))
                    return "(1 = 1)";

                if (left == null || string.Equals(left, "null", StringComparison.OrdinalIgnoreCase))
                    return $"({right} IS NULL)";
                if (right == null || string.Equals(right, "null", StringComparison.OrdinalIgnoreCase))
                    return $"({left} IS NULL)";
                return $"({left} = {right})";
            }
            if (expression.Method.DeclaringType == typeof(string))
            {
                switch (expression.Method.Name)
                {
                    case "ToUpper":
                        return $"UPPER({ConvertExpression(expression.Object)})";
                    case "Contains":
                        return
                            $"({ConvertExpression(expression.Object)} Like concat('%',{GetArguments(expression)},'%'))";
                    case "ToLower":
                        return $"LOWER({ConvertExpression(expression.Object)})";
                    case "Trim":
                        return $"TRIM({ConvertExpression(expression.Object)})";
                    case "TrimStart":
                        return $"LTRIM({ConvertExpression(expression.Object)})";
                    case "TrimEnd":
                        return $"RTRIM({ConvertExpression(expression.Object)})";
                    case "Replace":
                        return $"REPLACE({ConvertExpression(expression.Object)},{GetArguments(expression)})";
                }
                throw new ArgumentException("��֧�ַ���");
            }
            if (expression.Method.DeclaringType == typeof(Math))
            {
                switch (expression.Method.Name)
                {
                    case "Abs":
                        return $"ABS({GetArguments(expression)})";
                }
            }
            if (expression.Method.DeclaringType == typeof(Enum))
            {
                switch (expression.Method.Name)
                {
                    case "HasFlag":
                        return string.Format("({0} & {1}) = {1}", ConvertExpression(expression.Object), GetArguments(expression));
                }
            }

            if (expression.Method.DeclaringType.IsGenericType && expression.Method.DeclaringType.GetGenericTypeDefinition() == typeof(List<>))
            {
                switch (expression.Method.Name)
                {
                    case "Contains":
                        var vl = ConvertExpression(expression.Object);
                        if (!string.IsNullOrWhiteSpace(vl))
                            return $"{GetArguments(expression)} in ({vl})";
                        else
                            return null;
                }
            }
            var name = _condition.AddParameter(GetValue(expression));
            return $"?{name}";
        }

19 View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private void ReadEnreplacedy(TypeDoreplacedent typeDoreplacedent, Type type)
        {
            if (type == null || type.IsAutoClreplaced || !IsLetter(type.Name[0]) ||
                type.IsInterface || type.IsMarshalByRef || type.IsCOMObject ||
                type == typeof(object) || type == typeof(void) ||
                type == typeof(ValueType) || type == typeof(Type) || type == typeof(Enum) ||
                type.Namespace == "System" || type.Namespace?.Contains("System.") == true)
                return;
            if (typeDocs.TryGetValue(type, out var doc))
            {
                foreach (var field in doc.Fields)
                {
                    if (typeDoreplacedent.Fields.ContainsKey(field.Key))
                        typeDoreplacedent.Fields[field.Key] = field.Value;
                    else
                        typeDoreplacedent.Fields.Add(field.Key, field.Value);
                }
                return;
            }
            if (typeDocs2.TryGetValue(type, out var _))
            {
                ZeroTrace.WriteError("ReadEnreplacedy", "over flow", type.Name);

                return;
            }

            typeDocs2.Add(type, typeDoreplacedent);
            if (type.IsArray)
            {
                ReadEnreplacedy(typeDoreplacedent, type.replacedembly.GetType(type.FullName.Split('[')[0]));
                return;
            }
            if (type.IsGenericType && !type.IsValueType &&
                type.GetGenericTypeDefinition().GetInterface(typeof(IEnumerable<>).FullName) != null)
            {
                ReadEnreplacedy(typeDoreplacedent, type.GetGenericArguments().Last());
                return;
            }

            XmlMember.Find(type);
            if (type.IsEnum)
            {
                foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
                {
                    if (field.IsSpecialName)
                    {
                        continue;
                    }
                    var info = CheckMember(typeDoreplacedent, type, field, field.FieldType, false, false, false);
                    if (info != null)
                    {
                        info.TypeName = "int";
                        info.Example = ((int)field.GetValue(null)).ToString();
                        info.JsonName = null;
                    }
                }
                typeDocs.Add(type, new TypeDoreplacedent
                {
                    fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
                });
                typeDoreplacedent.Copy(XmlMember.Find(type));
                return;
            }

            var dc = type.GetAttribute<DataContractAttribute>();
            var jo = type.GetAttribute<JsonObjectAttribute>();

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, property, property.PropertyType, jo != null, dc != null);
            }
            foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (!char.IsLetter(field.Name[0]) || field.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, field, field.FieldType, jo != null, dc != null);
            }

            typeDocs.Add(type, new TypeDoreplacedent
            {
                fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
            });
            typeDoreplacedent.Copy(XmlMember.Find(type));
        }

See More Examples