Array of objects - modyfing object's fields C#

后端 未结 6 701
滥情空心
滥情空心 2021-01-29 06:59

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. Construct

相关标签:
6条回答
  • 2021-01-29 07:14

    It's an array of objects and as the error message suggests, 'object' does not contain a definition for 'age'

    You need to declare your array with the type that has age field or property.And the you can modify it whatever you want. For example:

    class Person 
    {
        public string Name { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-29 07:16

    First you need to cast the object to the type you're intending to work with.

    If you work with type object, it has only a limited amount of properties and methods. To use property age, you first need to cast it to the corresponding type that has that property. For instance something like this:

    static Object[] prac = new Object[10];
    public static void Main(string[] args)
    {
        SpecificType myObject = prac[0] as SpecificType; // returns null if not successful
        if (myObject != null)
            myObject.age = 21;
    }
    

    HOWEVER, I'm not convinced you're doing the right thing here. I'd personally avoid type object unless absolutely there would be no other way of doing it (and that is very rare in my code). C# is a strongly-type language and by using object you're prone to errors all over the place.

    0 讨论(0)
  • 2021-01-29 07:18

    Object is the base class for all classes in .Net.

    Just cast the required value to the required typed class. Or Create a list with the right type instead of object.

    0 讨论(0)
  • 2021-01-29 07:21

    You have to use an array of your class instead of Object which is the base type of all classes.

    static MyClass[] prac = new MyClass[10];
    

    or you have to cast it:

    MyClass mc = (MyClass) prac[0];
    mc.age = 21;
    
    0 讨论(0)
  • 2021-01-29 07:25

    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;
    }
    

    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.

    0 讨论(0)
  • 2021-01-29 07:26

    Object doesn't have property age. All Object's properties and methods are stated here.

    0 讨论(0)
提交回复
热议问题