Accessing an Object in a General Method

How to access the property of an object inside a common method?
I can’t use where T: Ait because this method will get different objects, but all objects have a common property to work with.
(I also can not make a common interface for them)

public class A
{
    public int Number {get;set;}
}


List<A> listA = new List<A>{
                new A {Number =4},
                new A {Number =1},
                new A {Number =5}
};

Work<A>(listA);

public static void Work<T>(List<T> list1)
{
    foreach(T item in list1)
    {
        do something with item.Number;
    }
}

Update: I need to set property as well

+3
source share
2 answers

You have several options:

  • Create a common interface.
  • Use reflection.
  • Use the dynamic type in .NET 4.

, , , , , , , , . , , . , , :

1:

// Automatically generated code that you can't change.
partial class A
{
    public int Number { get; set; }
}

2:

interface IHasNumber
{
    int Number { get; set; }
}

partial class A : IHasNumber
{
}

, - , .

, :

where T : IHasNumber
+8

- , :

static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA.Select(a => a.Number));

}
public static void Work(IEnumerable<int> items)
{
    foreach (number item in items)
    {
        // do something with number;
    }
}

- :

static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA, a => a.Number);

}
public static void Work<T>(IList<T> list, Func<T, int> selector)
{
    foreach (T obj in list)
    {
        int number = selector(obj);
        // do something with number;
    }
}
+1

Source: https://habr.com/ru/post/1787263/


All Articles