Get Primitive Wrapper Property Or Field - CSharp System.Reflection

CSharp examples for System.Reflection:PropertyInfo

Description

Get Primitive Wrapper Property Or Field

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using System.IO;//from w  w w . j av  a2s. c  om
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        public static MemberInfo GetPrimitiveWrapperPropertyOrField(this Type primitiveWrapperType)
        {
            var members = primitiveWrapperType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

            var candidates =
                members.Where(
                    m =>
                    {
                        var f = m as FieldInfo;
                        if (f != null)
                            return f.GetCustomAttribute<CompilerGeneratedAttribute>() == null && f.FieldType.IsPrimitiveType();
                        var p = m as PropertyInfo;
                        if (p != null)
                            return p.PropertyType.IsPrimitiveType();
                        return false;
                    }
                );

            var candidateCount = candidates.Count();

            if(candidateCount != 1)
            {
                throw new ConstructionException("Primitive wrappers can only have 1 declared primitive member, found " + candidateCount + " for " + primitiveWrapperType.Name);
            }

            return candidates.Single();
        }
        public static bool IsPrimitiveType(this Type t)
        {
            return
                t == typeof(string) ||
                t == typeof(char) ||
                t == typeof(float) ||
                t == typeof(double) ||
                t == typeof(decimal) ||
                t == typeof(byte) ||
                t == typeof(sbyte) ||
                t == typeof(short) ||
                t == typeof(ushort) ||
                t == typeof(int) ||
                t == typeof(uint) ||
                t == typeof(long) ||
                t == typeof(ulong) ||
                t == typeof(bool) ||
                t == typeof(DateTime) ||
                t == typeof(DateTimeOffset) ||
                t == typeof(Guid) ||
                t == typeof(TimeSpan);
        }
}

Related Tutorials