简体   繁体   中英

Check if an object is non-basetype?

I want to be able to see if an object is of a base type (char, int, var, string (is this a base type in C#?)). The reason for this is because I want to create a parser, which gets the fields of the object and if it comes across an object it cannot get a value out of (if it was another object inside), it will recursively get the fields out of there too. So for instance:

    for (int x = 0; x < elements.Length; x++)
    {
        FieldInfo currenField = fields[x];

        if (currenField is object) //This doesn't work because its of type "FieldInfo"
        {
            //pass in the current object into the function
        }
        else
        {
            elements[x] = new XElement(currenField.Name, currenField.GetValue(obj).ToString());
        }

unfortunately I cannot seem to find anything online this will allow you to easily figure out if its a base type. The following is not possible either:

      currenField.GetType is typeof(object)

TLDR; I cannot determine if something is a base type or not, nor can I compare types to produce the same effect

Any help is greatly appreciated!

What you are referring to as "basic types" are actually considered Primitive Types. You can determine if a type is a Primitive Type by using the IsPrimitive property:

var type = currenField.GetType();
if(type.IsPrimitive)
    // Primitive type
else
    // Other type

Usually IsPrimitive is enough, but if you need more information, I'd recommend Type.GetTypeCode() .

var typeCode = Type.GetTypeCode(currenField.GetType());

switch (typeCode)
{
    case TypeCode.Boolean:
        break;
    case TypeCode.Byte:
        break;
    case TypeCode.Char:
        break;
    case TypeCode.DBNull:
        break;
    case TypeCode.DateTime:
        break;
    case TypeCode.Decimal:
        break;
    case TypeCode.Double:
        break;
    case TypeCode.Empty:
        break;
    case TypeCode.Int16:
        break;
    case TypeCode.Int32:
        break;
    case TypeCode.Int64:
        break;
    case TypeCode.Object:
        break;
    case TypeCode.SByte:
        break;
    case TypeCode.Single:
        break;
    case TypeCode.String:
        break;
    case TypeCode.UInt16:
        break;
    case TypeCode.UInt32:
        break;
    case TypeCode.UInt64:
        break;
    default:
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM