我是 Asp .net C# 新手。我对对象和继承有疑问。 如果我的父类(基表)有 2 个子类(信用卡表、银行账户表),我会很开心。在另一个从基表类获取对象的类中。 我的问题是我想知道基表是信用卡还是银行帐户?!
class BaseTable
{
string date;
public string Date
{
get { return date; }
set { date = value; }
}
string description;
public string Description
{
get { return description; }
set { description = value; }
}
}
class CreditCardTable:BaseTable
{
string Amount;
public string amount
{
get { return Amount; }
set { Amount = value; }
}
string Type;
public string type
{
get { return Type; }
set { Type = value; }
}
}
class BankAccountTable:BaseTable
{
string Refr;
public string Ref
{
get { return Refr; }
set { Refr = value; }
}
string debit;
public string Debit
{
get { return debit; }
set { debit = value; }
}
string credit;
public string Credit
{
get { return credit; }
set { credit = value; }
}
}
最佳答案
3 个选项:
使用
is
、as
或GetType()
显式检查给定实例的类型,以进行测试它针对一些已知类型if(obj is CreditCardTable) {...} else ...
向基本类型添加一个
虚拟
或抽象
方法,并使用该方法而不而不必担心哪个是的(因为它会自动调用最派生的覆盖
)obj.SomeMethod();
向
BaseTable
添加一个鉴别器 - 可能是一个虚拟
枚举属性,所有派生类型都从中返回不同的值,并且switch
关于该鉴别器:switch(obj.Type) { ... }
关于c# - Asp.Net C# 对象相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17318478/