這是我長時間檢查這個奇妙的網頁後的第一個問題。幾個特定的方法或一個通用的方法?
大概我的問題有點傻,但我想知道別人對此的看法。有什麼更好的辦法來創建幾種特定的方法,或者另一方面,只有一種通用的方法?下面是一個例子...
unsigned char *Method1(CommandTypeEnum command, ParamsCommand1Struct *params)
{
if(params == NULL) return NULL;
// Construct a string (command) with those specific params (params->element1, ...)
return buffer; // buffer is a member of the class
}
unsigned char *Method2(CommandTypeEnum command, ParamsCommand2Struct *params)
{
...
}
unsigned char *Method3(CommandTypeEnum command, ParamsCommand3Struct *params)
{
...
}
unsigned char *Method4(CommandTypeEnum command, ParamsCommand4Struct *params)
{
...
}
或
unsigned char *Method(CommandTypeEnum command, void *params)
{
switch(command)
{
case CMD_1:
{
if(params == NULL) return NULL;
ParamsCommand1Struct *value = (ParamsCommand1Struct *) params;
// Construct a string (command) with those specific params (params->element1, ...)
return buffer;
}
break;
// ...
default:
break;
}
}
我真的不喜歡後一種選擇的主要事情是這樣的,
ParamsCommand1Struct *value = (ParamsCommand1Struct *) params;
因爲 「PARAMS」 不能是指向「ParamsCommand1Struct」的指針,而是指向「ParamsCommand2Struct」或其他人的指針。
我真的很感謝你的意見!
你使用C還是C++?答案取決於你實際使用的是哪一種。 –
C++在這種情況下...... – kazbeel