This example describes the. NET to judge whether an object is a numerical type of method, share for everyone for reference. The implementation methods are as follows:
. NET determines whether an object is a numeric type at first glance it's a simple thing to do, but suddenly it's a bit overwhelming.
The first of course is to get its type information through the GetType () method reflection, and then analyze it, but the type information type does not simply give such a property to be judged.
The method given by the foreigner is:
Copy Code code as follows:
public static bool IsNumeric (this Type dataType)
{
if (DataType = null)
throw new ArgumentNullException ("DataType");
return (DataType = = typeof (int)
|| DataType = = typeof (Double)
|| DataType = = typeof (Long)
|| DataType = = typeof (short)
|| DataType = = typeof (float)
|| DataType = = typeof (Int16)
|| DataType = = typeof (Int32)
|| DataType = = typeof (Int64)
|| DataType = = typeof (UINT)
|| DataType = = typeof (UInt16)
|| DataType = = typeof (UInt32)
|| DataType = = typeof (UInt64)
|| DataType = = typeof (SByte)
|| DataType = = typeof (Single)
);
}
He was trying to be exhaustive than to all known numeric types .... This should be possible, that is, performance almost and indecent bar.
and ~ He seems to have forgotten the decimal ...
Further study of these numerical types, which appear to be structs rather than classes, have a common interface:
IFormattable, IComparable, iconvertible
Where the IFormattable interface is an interface with a numeric type that differs from several other underlying types.
This is very good to do, the code is as follows:
Copy Code code as follows:
public static bool Isnumerictype (this Type o)
{
return!o.isclass &&!o.isinterface && o.getinterfaces (). Any (q => q = = typeof (IFormattable));
}
In addition to the basic types, there are nullable type Nullable<t> this, for generic types of matching I do not know what to do, in a hurry did not delve into, with a lazy way to achieve:
Copy Code code as follows:
public static bool Isnullablenumerictype (this Type o)
{
if (!o.name.startswith ("Nullable")) return false;
return o.getgenericarguments () [0]. Isnumerictype ();
}
See, just to judge the type name is not started with "Nullable", if it is then the first generic parameter type of the above judgment, this is certainly not 100% reliable, interested friends can further refine this method.
I hope this article will help you with your. NET programming.