对象数组-modyfing对象的字段C# [英] Array of objects - modyfing object's fields C#

查看:70
本文介绍了对象数组-modyfing对象的字段C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这样的问题.我是C#的初学者.我有一个对象数组(各种类),在一个应用程序中,我想修改年龄或姓名等字段.施工

I've got such a problem. I'm a beginner in C#. I have an object array (various classes) and in one place of application I want to modify fields like an age or name. Construction

static Object[] prac = new Object[10];
public static void Main(string[] args)
{
    prac[0].age = 21;
}

大喊错误

对象"不包含年龄"的定义,也找不到找到接受对象"类型的第一个参数的扩展方法年龄"

'object' does not contain a definition for 'age' and no extension method 'age' accepting a first argument of type 'object' could be found

我认为这将类似于Java代码,但事实并非如此.我究竟做错了什么?

I thought that will be similiar to a Java code, but it isn't. What am I doing wrong?

致谢.

推荐答案

您需要将成员强制转换为包含年龄的类类型.我只是假设您的班级名称是 Person ,并且具有 age 成员:

You need to cast your member to the class type that contains the age. I'll just assume that your class name is Person and that is has a age member :

static Object[] prac = new Object[10];
public static void Main(string[] args)
{
    ((Person)prac[0]).age = 21;
}

需要注意的是方括号:(Person)prac [0] 是转换部分,您转换 Object prac [0] Person 对象.外括号((Person)prac [0])在那里,因此代码被视为 Person 对象,而不是常规的 Object .

Important to note are the brackets : (Person)prac[0] is the cast part, you cast the Object prac[0] to a Person object. The outer brackets ((Person)prac[0]) are there so that the code is taken as a Person object, instead of a regular Object.

这篇关于对象数组-modyfing对象的字段C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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