У меня есть следующий сценарий:Определить члена класса от типа
1) Класс:
public class C
{
public List<MyType> ListOfMyTypeObjects;
public List<MyOtherType> ListOfMyOtherTypeObjects;
public C()
{
this.ListOfMyTypeObjects = new List<MyType>;
this.ListOfMyOtherTypeObjects = new List<MyOtherType>;
}
}
2) Интерфейс:
public interface IInterface<T>
{
object CreateObject(T source);
}
3) Реализация класса:
public class Implementing<T> : IInterface<T> where T: SomeGeneralType
{
public object CreateObject(T source, int key)
{
//i know T can be of type MyType, but it can also be MyOtherType
C c = (C)storage[key];
//here, i would like to add to one of my members the source object,
//but without specifically know it is called that; in other words, i would like
//to scan c and find if it has any List<T> members; in that case, add to the
//found member (which is unique) the source object and return something,
//doesn't matter what
}
}
4) Объект экземпляра:
IDicionary<int, C> storage = new Dictionary{{1, new C()}};
Как я могу определить элемент, который соответствует желаемому типу, и как я могу добавить к нему объект?
Чтобы получить тип из общего «Т», вы можете использовать «typeof»: Type givenType = typeof (T); –