Is there a less convoluted way to compare file versions?

五迷三道 提交于 2019-12-01 21:06:24
Servy

Use the Version class:

Version first = new Version("1.1.2.1");
Version second = new Version("2.1.1.1");
bool b = first >= second;
Jim Mischel

Servy's answer is the one you should go with.

However, for other situations when you have nested criteria and you don't have the benefit of a class that already implements the comparison, the most straightforward way to do it is to use multiple conditionals and "early out" as soon as you can. For example, when checking versions you could do this:

if (FileMajorClient > FileMajorServer)
    return false;
if (FileMajorClient < FileMajorServer)
    return true;

// Major versions are equal, now do the same thing for minor part
if (FileMinorClient != FileMinorServer)
    return (FileMinorClient < FileMinorServer);

Note that the major version check could have been written the same way as the minor version check. It's just two different ways of writing the same logic.

You can then do that for each of the remaining parts.

if (FileBuildPartClient != FileBuildPartServer)
    return (FileBuildPartClient < FileBuildPartServer);

return (FilePrivatePartClient <= FilePrivatePartServer);

At each step you have eliminated the cases where the client and server versions don't match.

This isn't as "clever" as writing a monolithic conditional statement, but it's easy to understand and easy to prove correct.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!