检查类型最快的方法是什么? [英] What is the fastest way to check a type?
问题描述
我决定在一个函数中检查类型,而不是将函数重载100次或为不同类型创建100个不同的比较器.
Instead of overloading a function 100 times or creating 100 different Comparers for different types I've decided to check the type within one function.
例如,我正在使用默认比较器来比较2个对象内的一组类型(基元和字符串)的值.它包含以下代码:
For example I'm using a default comparer to compare values of a set of types (primitives and strings) within 2 objects. It contains the following code:
public class DefComparer : IComparer<object> {
public int Compare(object a, object b) {
.... // a = a.GetType().GetField(field).GetValue(a); - not important for the question but I'm just showing that a&b below are different references
switch (a.GetType().Name) {
case "Byte":
if ((byte)a == (byte)b) return 0;
else if ((byte)a > (byte)b) return 1;
else return -1;
case "UInt16":
if ((ushort)a == (ushort)b) return 0;
else if ((ushort)a > (ushort)b) return 1;
else return -1;
case "SByte":
if ((sbyte)a == (sbyte)b) return 0;
else if ((sbyte)a > (sbyte)b) return 1;
else return -1;
case "Int16":
...
这里我使用的是一个 switch
语句,据说它比 if
/ else
语句链要快.但是 a.GetType().Name
返回一个动态获取的字符串,并且此方法涉及字符串比较.在我看来,这听起来并不快.我需要比较器在技术上尽可能快,因为它将用于大量数据.
Here I'm using a switch
statement that is said to be faster than a chain of if
/else
statements. But a.GetType().Name
returns a string that is dynamically obtained and this method involves string comparisons. That doesn't sound particularly fast to me. I need the Comparer to be as fast as technically possible because It's going to be used on large collections of data.
问:有没有更快的方法来检查对象的类型(不涉及字符串比较)?最快的方法是什么?
推荐答案
好了.使用 TypeCode
int a = 10;
Type t = a.GetType();
switch (Type.GetTypeCode(t))
{
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;
}
这支持所有原语.用于自定义对象在 TypeCode.Object
内写 else if
语句.
this supports all primitives. for Custom objects Write else if
statements inside TypeCode.Object
.
我希望这会有所帮助.
这篇关于检查类型最快的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!