Generic type checking

前端 未结 8 1427
既然无缘
既然无缘 2020-12-22 17:10

Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.)

Now, I know you can limit the generic typ

8条回答
  •  萌比男神i
    2020-12-22 17:47

    Primitives appear to be specified in the TypeCode enumeration:

    Perhaps there is a way to find out if an object contains the TypeCode enum without having to cast it to an specific object or call GetType() or typeof()?

    Update It was right under my nose. The code sample there shows this:

    static void WriteObjectInfo(object testObject)
    {
        TypeCode    typeCode = Type.GetTypeCode( testObject.GetType() );
    
        switch( typeCode )
        {
            case TypeCode.Boolean:
                Console.WriteLine("Boolean: {0}", testObject);
                break;
    
            case TypeCode.Double:
                Console.WriteLine("Double: {0}", testObject);
                break;
    
            default:
                Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
                break;
            }
        }
    }
    

    It's still an ugly switch. But it's a good place to start!

提交回复
热议问题