Answer the question
In order to leave comments, you need to log in
How to call a class method if T is passed as a type parameter?
There are two classes:
public class Student
{
public static Student Parse(string str)
{
Student s = new Student();
return s;
}
}
public class Teacher
{
public static Teacher Parse(string str)
{
Teacher t = new Teacher();
return t;
}
}
static void ReadFile<T>(string file, University u)
{
using (var sr = new StreamReader(file, Encoding.GetEncoding("windows-1251")))
{
string str = "";
int lineNumber = 1;
while ((str = sr.ReadLine()) != null)
{
if (T.Parse(str) != null) // Parse вернет null, если строка некорректна
u.Add(T.Parse(str)); // в University добавляется готовый объект
else
Console.WriteLine("Некорректно введенные данные в файле in.txt в строке " + lineNumber);
lineNumber++;
}
}
}
Answer the question
In order to leave comments, you need to log in
Now - no way. Generics do not hide static methods in any way. (but such a feature will be in .net 7 or experimental features in .net 6)
Try to rewrite the code so that there are no statics.
T is not known in advance, but is it possible to write some construction so that already in the process of program execution, using the passed parameter T, access the Parse function? (or stop the execution of the subroutine if T is incorrect)
Dictionary<Type, IParser> parsers
interface IParser { object Parse(string str); }
var parser = parsers[typeof(T)];
if(parser.Parse(str) is T data)
u.Add(data);
else
Console.WriteLine("Некорректно введенные данные в файле in.txt в строке " + lineNumber);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question