A
A
Anonymous123443212021-10-01 19:24:48
C++ / C#
Anonymous12344321, 2021-10-01 19:24:48

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;
        }
    }

These classes have a Parse method that takes a string from a file and, after checking (not shown here), creates an instance of the current class with the data from the string passed to its constructor and returns it. To read data from a file, to avoid code duplication, a function was created
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++;
                }
            }
        }


There are two files for storing student and teacher data, teachers.txt and students.txt. Teachers and students have different data in the files. The problem is that either Student or Teacher will be passed to the ReadFile function instead of T. But how to refer to their static Parse method in the loop body in the conditional statement? (There is an error in the above code). That is, it is impossible to turn to T.Parse(), because 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)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-10-01
@vabka

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)

Store somewhere Dictionary<Type, IParser> parsers
Which IParser - Then there will be something like this: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 question

Ask a Question

731 491 924 answers to any question