VC2005中扩展了动态创建CObject派生类的功能,这非常有用,在应用程序中实现二次开发,可以动态创建控件类,可以动态创建模块类,可以动态创建用户自定义类,只要知道类的名字即可:
Call this function to retrieve the CRuntimeClass structure associated with the familiar name.
|
static CRuntimeClass* PASCAL FromName(
LPCSTR
lpszClassName
);
static CRuntimeClass* PASCAL FromName(
LPCWSTR
lpszClassName
);
|
Parameters
lpszClassName
The familiar name of a class derived from CObject.
Return Value
A pointer to a CRuntimeClass object, corresponding to the name as passed in lpszClassName. The function returns NULL if no matching class name was found.
Example
|
Copy Code
|
// This example creates an object if CMyClass is defined.
CRuntimeClass* pMyRTClass= pMyObject->GetRuntimeClass();
CRuntimeClass* pClass = pMyRTClass->FromName("CMyClass");
if (pClass == NULL)
{
// not found, display a warning for diagnostic purposes
AfxMessageBox("Warning: CMyClass not defined");
return NULL;
}
// attempt to create the object with the found CRuntimeClass
CObject* pObject = pClass->CreateObject();
|
Remarks
This method is not supported on Smart Devices because, in order for this method to return a class object, the returned class must use the
DECLARE_SERIAL
,
IMPLEMENT_SERIAL
macros, which are not supported for devices.
See Also
Reference
CMyClass * pMyObject=new CMyClass;
CRuntimeClass* pMyRTClass= pMyObject->GetRuntimeClass();
CRuntimeClass* pClass = pMyRTClass->FromName("CMyClass");
CRuntimeClass* pClass0 = CRuntimeClass::FromName("CMyClass");
// TODO:
在此添加命令处理程序代码
//CRuntimeClass* pRuntimeClass = CRuntimeClass::FromName("CRunTimeDoc");// RUNTIME_CLASS( CRunTimeDoc );
CRuntimeClass* pRuntimeClass = RUNTIME_CLASS( CMyClass );
//CObject* pObject = pRuntimeClass->CreateObject("CMyClass");
CObject* pObject = CRuntimeClass::CreateObject("CMyClass");
//CObject* pObject = pRuntimeClass->CreateObject();
ASSERT( pObject->IsKindOf( RUNTIME_CLASS( CMyClass ) ) );
注意,CMyClass必须从CObject派生必须实现了DECLARE_SERIAL, IMPLEMENT_SERIAL两个宏。