我无法理解继承的 get
方法中 base
和 this
的正确使用。我有一个接口(interface)IMatchModel
:
public interface IMatchModel
{
int TypeId { get; }
DateTime DataDate { get; set; }
string TypeName { get; set; }
}
还有一个基本模型类TradeModel
:
public class TradeModel
{
public long TradeId { get; set; }
public DateTime DataDate { get; set; }
public string TradeName { get; set; }
}
然后我有一个继承自 TradeModel
并实现 IMatchModel
的类。我目前正在使用以下方法:
public class TradeMatchModel : TradeModel, IMatchModel
{
public int TypeId { get { return 1; } }
public string TypeName
{
get
{
return base.TradeName;
}
set
{
base.TradeName = value;
}
}
}
TradeModel
类在对其所有属性进行操作的函数中使用。 IMatchModel
用于仅需要接口(interface)中包含的属性的函数。代码工作正常,但我仍然觉得我不太明白是否最好使用 base
而不是 this
。在此上下文中使用 base
是否不正确?
最佳答案
唯一需要使用base
的时候是当您位于重写的虚拟方法中并且需要调用当前正在重写的方法的基本实现时。其他时候您都可以使用this.
。
此外,通常不需要 this.
,除非类中的字段或属性与变量或参数的名称之间存在名称冲突。 99% 的情况下,您可以省略 this.
并执行 return TradeName;
关于C# 在继承 get 中使用 base 或 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46079920/