如何访问对象数组C#中的子类方法? [英] How to access methods of subclass in object array C#?

查看:110
本文介绍了如何访问对象数组C#中的子类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置/获取对象数组中对象的值?

How can I set/get the value of an object in an object array?

目前,我得到:对象不包含'value'的定义,也没有扩展方法"

示例C#;

    public class myObjClass
    {
        public int value = 5;
    }

    public class myObjClass2
    {
        public float[] pos = new float[2];
    }

    public void test()
    {
        myObjClass myObj = new myObjClass();
        myObjClass2 myObj2 = new myObjClass2();

        object[] objArr = new object[2];
        objArr[0] = myObj;
        objArr[1] = myObj2;
        Debug.Print(myObj.value.ToString());
        Debug.Print(objArr[0].value.ToString()); // how?

    }

推荐答案

这是因为通用 object 不具有类 myObjClass 的属性 value 代码>有.要解决此问题,您可以 广播 将该项目添加到您的班级中,如下所示:

Its because a generic object does not have the property value your class myObjClass has. To fix this you could cast the item to your class like so:

((myObjClass)objArr[0]).value.ToString()

仅当您确定类型为

相反,您也可以先进行检查:

使用 作为 :

With as:

var item = objArr[0] as myObjClass;
if( item != null ) // Item will be null if its not a 'myObjClass'
{
    //Do stuff with item
}

或使用 :

Or with is:

if( objArr[0] is myObjClass )
{
    var item = (myObjClass)objArr[0];
    //Do stuff with item
}

这篇关于如何访问对象数组C#中的子类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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