Version Numbers float, decimal or double

烂漫一生 提交于 2019-12-05 02:34:27

System.Version

This already stores the different parts, deals with presenting it as a string (revision and build components are only used in display if they are non-zero, so their irrelevance to your case doesn't matter) and (best of all) is already understood by other .NET developers, and won't lead to confusion (if I saw some use of a version number that wasn't a System.Version I'd spend some time then trying to work out why Version wasn't good enough for the job, in case that proved important and hid a nasty surprise. If it was good enough for the job, I'd be irritated at the developer wasting my time like that).

You can deal with the means you want for incrementing easily with extension methods:

public static Version IncrementMajor(this Version ver)
{
  return new Version(ver.Major + 1, 0);
}
public static Version IncrementMinor(this Version ver)
{
  return new Version(ver.Major, ver.Minor + 1);
}

How about two integers? One for major and one for minor revisions?

Make your own data type for this

public struct VersionNumber : IComparable<ReleaseNumber>
{
  public int MajorVersion{get;set;}
  public int MinorVersion{get;set;}

  public VersionNumber( int major, int minor)
  {
    MajorVersion = major;
    MinorVersion = minor;
  }

  public override string ToString(){
    return major + '.' + minor;
  }

  public int CompareTo(VersionNumber other) {
    int result;
    result = MajorVersion.CompareTo(other.MajorVersion);
    if (result != 0) { return result; }
    return MinorVersion.CompareTo(other.MinorVersion);
  }
  public static bool operator <(VersionNumber left, VersionNumber right) {
    return left.CompareTo(right) < 0;
  }
  public static bool operator <=(VersionNumber left, VersionNumber right) {
    return left.CompareTo(right) <= 0;
  }
  public static bool operator >(VersionNumber left, VersionNumber right) {
    return left.CompareTo(right) > 0;
  }
  public static bool operator >=(VersionNumber left, VersionNumber right) {
    return left.CompareTo(right) >= 0;
  }
}

You can also add a comparer so you can check two version numbers to see which one is the highest version of two version numbers for example.

EDIT

Added the comparer logic also for good measure :)

I would suggest two integers: a major and a minor. You can even store this as major * 1000 + minor if you want one variable.

Decimal should be the best of the above given, but as other has noted two ints would be better.

Doubles and floats does not accurately store all decimal values, you don't want your version to suddenly be 1.219999999999999999

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