Performing version checking between an abstract class and its implementation

I have this abstract class and a specific implementation (they are in different assemblies):

public abstract class MyAbstractClass { private static readonly int MyAbstractClassVersion = 1; public abstract int ImplementedVersion { get; } protected MyAbstractClass() { CheckVersion(); } private void CheckVersion() { var message = string.Format( "MyAbstractClass implements Version {0}, concrete is Version {1}", RepositoryVersion, ImplementedVersion); if (!MyAbstractClassVersion.Equals(ImplementedVersion)) throw new InvalidOperationException(message); } } public class ConcreteClass : MyAbstractClass { public ConcreteClass() : base() { // ConcreteClass is guaranteed to have // a constructor that calls the base constructor // I just simplified the example } public override int ImplementedVersion { get { return 2; } } } 

As you can see, I call the CheckVersion () function from the abstract constructor to get rid of the message “virtual member in the base constructor”, but I'm not sure if this is really a way to do this. Of course, this works, but that doesn’t mean that it will always work, right?

Also, I am wondering if I can get a Concrete type name from the CheckVersion () function?

I know that adding new abstract elements will still result in an error (System.TypeLoadException), and I'm not sure if I want this type of strict versioning Versioning, but I'm just wondering how it will be done correctly, the abstract class and implementation (I I know that I can do this using interfaces and / or the Factory template).

+4
source share
1 answer

Well, you are only fooling static analysis - you are still making a virtual call to ctor. If this is necessary during ctor, perhaps instead it should be the required value of the base constructor, this subclass goes down:

 protected BaseType(int version) { /* store etc */ } public DerivedType() : base(3) {...} 

Or perhaps do it in what is fixed at compilation - attributes:

 [YourVersion(3)] public class DerivedType {...} 

and view this using reflection on:

 YourVersionAttribute attrib = (YourVersionAttribute) Attribute.GetCustomAttribute(GetType(), typeof(YourVersionAttribute)); int version = attrib == null ? -1 : attrib.Version; 
+4
source

Source: https://habr.com/ru/post/1305349/


All Articles