您可以創建一個擴展方法爲您執行添加。仍然需要自定義代碼;但如果你在很多地方這樣做,有這樣一個輔助方法可能是有用的。以下是一些可能有用的功能。
public static class VersionExtension {
public static Version IncrementRevision(this Version version) {
return AddVersion(version, 0, 0, 0, 1);
}
public static Version IncrementBuild(this Version version) {
return IncrementBuild(version, true);
}
public static Version IncrementBuild(this Version version, bool resetLowerNumbers) {
return AddVersion(version, 0, 0, 1, resetLowerNumbers ? -version.Revision : 0);
}
public static Version IncrementMinor(this Version version) {
return IncrementMinor(version, true);
}
public static Version IncrementMinor(this Version version, bool resetLowerNumbers) {
return AddVersion(version, 0, 1, resetLowerNumbers ? -version.Build : 0, resetLowerNumbers ? -version.Revision : 0);
}
public static Version IncrementMajor(this Version version) {
return IncrementMajor(version, true);
}
public static Version IncrementMajor(this Version version, bool resetLowerNumbers) {
return AddVersion(version, 1, resetLowerNumbers ? -version.Minor : 0, resetLowerNumbers ? -version.Build : 0, resetLowerNumbers ? -version.Revision : 0);
}
public static Version AddVersion(this Version version, string addVersion) {
return AddVersion(version, new Version(addVersion));
}
public static Version AddVersion(this Version version, Version addVersion) {
return AddVersion(version, addVersion.Major, addVersion.Minor, addVersion.Build, addVersion.Revision);
}
public static Version AddVersion(this Version version, int major, int minor, int build, int revision) {
return SetVersion(version, version.Major + major, version.Minor + minor, version.Build + build, version.Revision + revision);
}
public static Version SetVersion(this Version version, int major, int minor, int build, int revision) {
return new Version(major, minor, build, revision);
}
/*
//one day we may even be able to do something like this...
//https://github.com/dotnet/csharplang/issues/192
public static Version operator +(Version version, int revision) {
return AddVersion(version, 0, 0, 0, revision);
}
public static Version operator ++(Version version) {
return IncrementVersion(version);
}
*/
}
示例用法
void Main()
{
Version myVersion = new Version ("1.2.3.4");
myVersion = myVersion.IncrementRevision();
Console.WriteLine(myVersion); //1.2.3.5
myVersion = myVersion.IncrementMinor();
Console.WriteLine(myVersion); //1.3.0.0
}
由於http://msdn.microsoft.com/en-us/library/system.version(V = vs.110的[System.Version](屬性).aspx)是隻讀的。爲什麼不能實現你自己的功能來分配值 – 2014-09-22 07:13:22
請你可以在這裏放一些示例代碼我如何實現我自己的功能? – 2014-09-22 07:16:08
這取決於你想要的格式。最簡單的就是將該值存儲爲int,然後將其增加。如果你真的想要像上面顯示的那樣,那麼你需要拆分字符串,將值轉換爲數字,增加一個或多個,然後將它們加回到字符串 – 2014-09-22 07:27:01