gpt4 book ai didi

c# - 在抽象类及其实现之间实现版本检查

转载 作者:太空狗 更新时间:2023-10-30 01:27:37 25 4
gpt4 key购买 nike

我有这个抽象类和具体实现(它们在不同的程序集中):

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; }
}
}

如您所见,我从抽象构造函数中调用了 CheckVersion(),以消除“基构造函数中的虚拟成员调用”消息,但我不确定这是否真的是这样做的方法。当然,它有效,但这并不意味着它会一直有效,对吗?

另外,我想知道是否可以从 CheckVersion() 函数中获取具体类型的名称?

我知道添加新的抽象成员无论如何都会导致错误(System.TypeLoadException),我不确定我是否需要这种类型的严格版本控制,但我只是好奇如果只给定抽象类和实现(我知道我可以通过使用接口(interface)和/或工厂模式来实现)。

最佳答案

好吧,您只是在欺骗静态分析 - 您仍在 ctor 中的虚拟调用。如果在 ctor 期间需要它,也许这应该是一个必需的基本构造函数值,子类向下传递:

protected BaseType(int version) { /* store etc */ }

public DerivedType() : base(3) {...}

或者也许在编译时固定的属性中执行此操作:

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

并通过反射(reflection)查找:

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

关于c# - 在抽象类及其实现之间实现版本检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2532426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com