gpt4 book ai didi

c# - 在构造函数中覆盖属性或计算属性

转载 作者:行者123 更新时间:2023-11-30 16:18:55 25 4
gpt4 key购买 nike

例如我有一个基类,我需要一个属性将在派生类中计算。我有两个变体(SomeProperty1SomeProperty2):

public class BaseClass
{
public int SomeProperty1{get;set;}
public override int SomeProperty2{get;set;}
}

public class DerivedClass : BaseClass
{
public DerivedClass()
{
SomeProperty1 = 100;
}
public override int SomeProperty2
{
get
{
return 100;
}
}
}

问题是什么是最好的方法,SomeProperty1 还是 SomeProperty2

最佳答案

向基类添加一个名为 CalcSomeProperty() 的 protected 抽象方法。

然后根据 CalcSomeProperty() 实现您的属性。这将强制派生类实现它。

例如:

public abstract class BaseClass
{
public int SomeProperty
{
get
{
return CalcSomeProperty();
}
}

protected abstract int CalcSomeProperty();
}

或者,您可以将属性本身抽象化:

public abstract class BaseClass
{
public abstract int SomeProperty { get; }
}

无论哪种情况,您都在强制派生类实现属性计算。

将计算分离到 protected 方法(而不是使用更简单的抽象属性)的一个优点是,如果计算速度慢,您可以在具体属性实现中执行缓存:

public abstract class BaseClass
{
protected BaseClass()
{
_someProperty = new Lazy<int>(CalcSomeProperty);
}

public int SomeProperty
{
get
{
return _someProperty.Value;
}
}

protected abstract int CalcSomeProperty();

private readonly Lazy<int> _someProperty;
}

关于c# - 在构造函数中覆盖属性或计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15741092/

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