今天在做一个windows平台的小工具顺便熟悉一下windows开发的一些基础知识,在这个过程中,发现了MFC使用了一种数据类型叫做COleVariant类型,感觉比较新鲜,赶忙到网上查一下,做一下记录,以备以后查看。
COleVariant类型的变量提供了一种强大的数据封装格式,可以将不同类型的数据用这一种变量表示,并且进行各种格式的转换也很方便。这个变量定义在afxdisp.h 中:
class COleVariant : public tagVARIANT { // Constructors public: COleVariant(); COleVariant(const VARIANT& varSrc); COleVariant(LPCVARIANT pSrc); COleVariant(const COleVariant& varSrc); COleVariant(LPCTSTR lpszSrc); COleVariant(LPCTSTR lpszSrc, VARTYPE vtSrc); // used to set to ANSI string COleVariant(CString& strSrc); COleVariant(BYTE nSrc); COleVariant(short nSrc, VARTYPE vtSrc = VT_I2); COleVariant(long lSrc, VARTYPE vtSrc = VT_I4); COleVariant(const COleCurrency& curSrc); #if (_WIN32_WINNT >= 0x0501) || defined(_ATL_SUPPORT_VT_I8) COleVariant(LONGLONG nSrc); COleVariant(ULONGLONG nSrc); #endif COleVariant(float fltSrc); COleVariant(double dblSrc); COleVariant(const COleDateTime& timeSrc); COleVariant(const CByteArray& arrSrc); COleVariant(const CLongBinary& lbSrc); COleVariant(LPCITEMIDLIST pidl); // Operations public: void Clear(); void ChangeType(VARTYPE vartype, LPVARIANT pSrc = NULL); void Attach(VARIANT& varSrc); VARIANT Detach(); void GetByteArrayFromVariantArray(CByteArray& bytes); BOOL operator==(const VARIANT& varSrc) const; BOOL operator==(LPCVARIANT pSrc) const; const COleVariant& operator=(const VARIANT& varSrc); const COleVariant& operator=(LPCVARIANT pSrc); const COleVariant& operator=(const COleVariant& varSrc); const COleVariant& operator=(const LPCTSTR lpszSrc); const COleVariant& operator=(const CString& strSrc); const COleVariant& operator=(BYTE nSrc); const COleVariant& operator=(short nSrc); const COleVariant& operator=(long lSrc); const COleVariant& operator=(const COleCurrency& curSrc); #if (_WIN32_WINNT >= 0x0501) || defined(_ATL_SUPPORT_VT_I8) const COleVariant& operator=(LONGLONG nSrc); const COleVariant& operator=(ULONGLONG nSrc); #endif const COleVariant& operator=(float fltSrc); const COleVariant& operator=(double dblSrc); const COleVariant& operator=(const COleDateTime& dateSrc); const COleVariant& operator=(const CByteArray& arrSrc); const COleVariant& operator=(const CLongBinary& lbSrc); void SetString(LPCTSTR lpszSrc, VARTYPE vtSrc); // used to set ANSI string operator LPVARIANT(); operator LPCVARIANT() const; // Implementation public: ~COleVariant(); };
COleVariant类型可以保存的数据有字符串、长短整型、浮点型、布尔型、日期等。从COleVariant变量导出数据也很方便,根据这篇参考文献的描述,可以使用以下方法很方便地将COleVariant转化为字符串:
switch(B.vt){ case VT_BSTR: A=V_BSTRT(&B); break;//COleVariant是一个字串 case VT_I2: A.Format(_T("%hd"),V_I2(&B));break;//是短整型 case VT_I4: A.Format(_T("%d"),V_I4(&B));break;//是长整型 case VT_R4: A.Format(_T("%e"),(double)V_R4(&B));break;//是浮点数 case VT_R8: A.Format(_T("%e"),V_R8(&B));break;//是浮点数 case VT_CY: A=COleCurrency(B).Format();break;//是货币值 case VT_DATE: A=COleDateTime(B).Format("%Y-%m-%d");break;//是日期 case VT_BOOL: A=V_BOOL(&B)?"True":"False";break;//是布尔值 }