简体   繁体   中英

C# Use class properties as array

I have a View Mode class.

public class VM_MyClass
{
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Display(Name = "Date Of Birth")]
    public string DOB { get; set; }
}

I want to use its attributes like this:

VM_MyClass model = new VM_MyClass();
model[0] = "Alpha" // Name
model[1] = "11/11/14" // DOB

Is there any possibility?

You can use an indexer and the reflection API like in the following example
(As other have said you must be very careful)

public class VM_MyClass
{
    private static Type ThisType = typeof(VM_MyClass);
    public string Name { get; set; }

    public DateTime DOB { get; set; }

    public object this[string propertyName]
    {
        get
        {
            return GetValueUsingReflection(propertyName);
        }
        set
        {

            SetValueUsingReflection(propertyName, value);
        }
    }

    private void SetValueUsingReflection(string propertyName, object value)
    {
        PropertyInfo pinfo = ThisType.GetProperty(propertyName);
        pinfo.SetValue(this, value, null);
    }
    private object GetValueUsingReflection(string propertyName)
    {
        PropertyInfo pinfo = ThisType.GetProperty(propertyName);
        return pinfo.GetValue(this,null);
    }
}

You can use it like this:

using System;
using System.Reflection;
namespace Example
{
  class Program
  {
    static void Main(string[] args)
    {
        VM_MyClass model = new VM_MyClass();

        model["Name"] = "My name";
        model["DOB"] = DateTime.Today;

        Console.WriteLine(model.Name);
        Console.WriteLine(model.DOB);
        //OR
        Console.WriteLine(model["Name"]);
        Console.WriteLine(model["DOB"]);

        Console.ReadLine();
    }
  }
}

@Georg Vovos, Thanks man for your answer, I also have solved it by this approach. As per my above comment I need to assign values of array to model attributes. So I found this way.

I am using your approach, which is more appropriate :) thanks for help.

    VM_MyClass model = new VM_MyClass();

    var ClassProperties = model.GetType().GetProperties();

    int counter = 0;
    foreach (var item in col)
    {
        Type type = model.GetType();

        System.Reflection.PropertyInfo propertyInfo = type.GetProperty(ClassProperties[counter].Name);

        propertyInfo.SetValue(model, item.InnerText);

        counter++;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM