목록을 사용자 정의하려고합니다. 나는 대부분 알아 내지 만 문제를 우연히 만난다. 다음은 작업중인 코드입니다.리스트 <T>을 어떻게 커스터마이징합니까?
public class MyT
{
public int ID { get; set; }
public MyT Set(string Line)
{
int x = 0;
this.ID = Convert.ToInt32(Line);
return this;
}
}
public class MyList<T> : List<T> where T : MyT, new()
{
internal T Add(T n)
{
Read();
Add(n);
return n;
}
internal MyList<T> Read()
{
Clear();
StreamReader sr = new StreamReader(@"../../Files/" + GetType().Name + ".txt");
while (!sr.EndOfStream)
Add(new T().Set(sr.ReadLine())); //<----Here is my error!
sr.Close();
return this;
}
}
public class Customer : MyT
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Item : MyT
{
public int ID { get; set; }
public string Category { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
public class MyClass
{
MyList<Customer> Customers = new MyList<Customer>();
MyList<Item> Items = new MyList<Item>();
}
코드에서 사용자 지정 목록을 만들려고하고 있습니다. 여기에도 내가 가지고있는 많은 수업 중 두 가지가 있습니다. 모든 클래스에는 ID가 있습니다. 모든 클래스가 사용자 지정 목록과 일치합니다. 문제가있는 것 같습니다. MyList<T>.Read()
- Add(new T().Set(sr.ReadLine()));
마지막으로 MyT를 T로 변환 할 수 없습니다. 해결 방법을 알아야합니다.
연장 방법은 아마 것 서브 클래 싱이 당신에게 정말로 중요한 것이 아니라면 더 좋습니다. –
'T : MyT'가 T가 'MyT'일 수만 있다면 왜 Generics를 사용합니까? – I4V
I4V : 내부 객체 만 사용하는 비 제네릭 대신 MyT로 컴파일되는 제네릭 버전을 사용합니다. 이는 캐스팅으로 인해 느려질 수 있습니다. MyText의 서브 클래스가있을 수 있습니다 ... –