在C#中的基类派生访问类的属性 [英] Accessing a property of derived class from the base class in C#

查看:112
本文介绍了在C#中的基类派生访问类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,什么是当泛型列表只包含基类访问派生类的属性的最佳方式。

 公共类ClassA的:BaseClass的
{
公共对象PropertyA {搞定;组; }
}

公共类ClassB的:BaseClass的
{
公共对象PropertyB {搞定;组; }
}

公共类BaseClass的
{
}

公共无效的主要
{
名单< BaseClass的> ; MYLIST =新的List<&的BaseClass GT;();
ClassA的一个=新ClassA的();
ClassB的B =新ClassB的();

MyList.Add(一);
MyList.Add(二);

的for(int i = 0; I< MyList.Count;我++)
{
//我想从派生类$ B $访问PropertyA ABD PropertyB b}
}


解决方案

当然,你可以向下转换,像这样:

 的for(int i = 0; I< MyList.Count;我++)
{
如果(MYLIST [i]为ClassA的)
{
VAR一个=((ClassA的)MYLIST [I])PropertyA。
//做一个
的东西}

如果(MYLIST [i]为ClassB的)
{
变种B =((ClassB的)MYLIST [ I])PropertyB。
//做B
}
}
的东西



。 。然而,你应该再看看你试图完成什么。如果您有需要去ClassA和ClassB的属性通用代码,那么你可能会更好包装获得这些属性成在父类的共享,虚拟财产或方法。



是这样的:

 公共类BaseClass的
{
公共虚拟无效DoStuff( ){}
}

公共类ClassA的:BaseClass的
{
公共对象PropertyA {搞定;组; }

公共覆盖无效DoStuff()
{
//做的东西与PropertyA
}
}

公共类ClassB的:BaseClass的
{
公共对象PropertyB {搞定;组; }

公共覆盖无效DoStuff()
{
//做的东西与PropertyB
}
}


In C#, what is the best way to access a property of the derived class when the generic list contains just the base class.

public class ClassA : BaseClass
{
   public object PropertyA { get; set; }
}

public class ClassB: BaseClass
{
    public object PropertyB { get; set; }
}

public class BaseClass
{
}

public void Main
{
    List<BaseClass> MyList = new List<BaseClass>();
    ClassA a = new ClassA();
    ClassB b = new ClassB();

    MyList.Add(a);
    MyList.Add(b);

    for(int i = 0; i < MyList.Count; i++)
    {
        //I would like to access PropertyA abd PropertyB from the derived classes        
    }
}

解决方案

Certainly you can downcast, like so:

for (int i = 0; i < MyList.Count; i++)
{
    if (MyList[i] is ClassA)
    {
        var a = ((ClassA)MyList[i]).PropertyA;
        // do stuff with a
    }

    if (MyList[i] is ClassB)
    {
        var b = ((ClassB)MyList[i]).PropertyB;
        // do stuff with b
    }
}

... However, you should take another look at what you're trying to accomplish. If you have common code that needs to get to properties of ClassA and ClassB, then you may be better off wrapping access to those properties up into a shared, virtual property or method in the ancestor class.

Something like:

public class BaseClass
{
    public virtual void DoStuff() { }
}

public class ClassA : BaseClass
{
    public object PropertyA { get; set; }

    public override void DoStuff() 
    {
        // do stuff with PropertyA 
    }
}

public class ClassB : BaseClass
{
    public object PropertyB { get; set; }

    public override void DoStuff() 
    {
        // do stuff with PropertyB
    }
}

这篇关于在C#中的基类派生访问类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆