C#-加载继承的类

本文关键字:继承 加载 C#- | 更新日期: 2023-09-27 18:25:08

我有一个名为FieldDesc的类。

public class FieldDesc {
    public FieldDesc() {
    }
}

我还有另一个从FieldDesc继承的类,叫做StandardHoursByCommunitySvcType

public class StandardHoursByCommunitySvcType: FieldDesc {
    public StandardHoursByCommunitySvcType() {
    }
}

在我的控制下,我有

FieldDesc aTable;
aTable = new FieldDesc();
String TableName = "StandardHoursByCommunitySvcType";

我必须做些什么才能让aTable知道它是StandardHoursByCommunitySvcType类型的对象?

C#-加载继承的类

您的问题不清楚。您是试图将表声明为StandardHoursByCommonySvcType,还是试图确定它是否已声明为一个?

如果您试图申报:

FieldDesc aTable;
aTable = new StandardHoursByCommunitySvcType();

只要StandardHoursByCommunitySvcType从FieldDesc 继承,它就可以工作

如果您试图确定类型:

if(aTable is StandardHoursByCommunitySvcType)
{
    //Do something
}

如果您有两个类

public class FieldDesc
{
    public FieldDesc()
    {
    }
    public void A()
    {
    }
    public virtual void V()
    {
        Console.WriteLine("V from FieldDesc");
    }
}
public class StandardHoursByCommunitySvcType : FieldDesc
{
    public StandardHoursByCommunitySvcType()
    {
    }
    public void B()
    {
    }
    public overrides void V()
    {
        Console.WriteLine("V from StandardHoursByCommunitySvcType");
    }
}

你可以做这个

FieldDesc fd = new StandardHoursByCommunitySvcType();
StandardHoursByCommunitySvcType svc = new StandardHoursByCommunitySvcType();
fd.A(); // OK
fd.B(); // Fails (does not compile)
((StandardHoursByCommunitySvcType)fd).B(); // OK
fd.V(); // OK, prints "V from StandardHoursByCommunitySvcType"
svc.A(); // OK
svc.B(); // OK
svc.V(); // OK, prints "V from StandardHoursByCommunitySvcType"

派生类与基类的赋值兼容;但是,通过一个类型化为基类的变量访问时,您将只能看到基类的成员。

您可以使用is运算符来查找

if(someObject is StandardHoursByCommunitySvcType )
    {
       //it means is is object of StandardHoursByCommunitySvcType  type
    }