Last active
July 24, 2017 22:45
-
-
Save lucasmeijer/154e89271d3c738c26f69a1b750f476d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Problem: have a XCodeCompilerSettings class and CppCompilerSettings base class, that both provide a .With() method to | |
//create a copy and change a setting. C# wizards of the internet, surely this can be done more elegantly! | |
using System; | |
public class CompilerSettings | |
{ | |
internal object MemberWiseClone() => base.MemberwiseClone(); | |
internal static T CloneAndModify<T>(T _this, Action<T> callback) where T : CppCompilerSettings | |
{ | |
var copy = (T) _this.MemberWiseClone(); | |
callback(copy); | |
return copy; | |
} | |
} | |
public class CppCompilerSettings : CompilerSettings | |
{ | |
public bool Exceptions { get; internal set; } | |
} | |
public static class CppCompilerSettingsExtensions | |
{ | |
//The With___ methods of base classes have to be done in an extension method like this, as it's the only | |
//way to make them return the actual type of the derived class. | |
public static T WithExceptions<T>(this T _this, bool value) where T : CppCompilerSettings | |
{ | |
return _this.Exceptions == value ? _this : CompilerSettings.CloneAndModify(_this, c=>c.Exceptions = value); | |
} | |
} | |
class XCodeClangSettings : CppCompilerSettings | |
{ | |
public bool Arc { get; internal set; } | |
//With___ methods that are in leaf compilersettings classes can be regular instance methods | |
public XCodeClangSettings WithExceptions(bool value) | |
{ | |
return Arc == value ? this : CloneAndModify(this, c=>c.Exceptions = value); | |
} | |
} | |
class Test | |
{ | |
static void Main() | |
{ | |
XCodeClangSettings xcodeSettings = new XCodeClangSettings(); | |
//the hard part is making WithExceptions return XCodeClangSettings instead of a CppCompilerSettings | |
XCodeClangSettings copy = xcodeSettings.WithExceptions(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If CppCompilerSettings strongly requires an instance method, Why not just put a generic method directly n CppCompilerSettings and remove extension method + xcodeclang method?