gpt4 book ai didi

C# 在继承 get 中使用 base 或 this

转载 作者:行者123 更新时间:2023-11-30 23:09:04 24 4
gpt4 key购买 nike

我无法理解在继承的 get 方法中正确使用 basethis 。我有一个接口(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/

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