Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在读取流时确定T.TryParse的正确T_C# - Fatal编程技术网

C# 在读取流时确定T.TryParse的正确T

C# 在读取流时确定T.TryParse的正确T,c#,C#,我有一个方法,可以从传递的字符串中输入文本文件,必须检查传递类型的TryParse是否可以从流中读取字符串,然后将项添加到传递的组合框中 我试着这么做,但一直在思考如何通过打字,然后检查TryParse private void Input(string file, ComboBox cb, /* object passedType */) { if (File.Exists(c + "recent_IPs.txt")) {

我有一个方法,可以从传递的字符串中输入文本文件,必须检查传递类型的TryParse是否可以从流中读取字符串,然后将项添加到传递的组合框中

我试着这么做,但一直在思考如何通过打字,然后检查TryParse

private void Input(string file, ComboBox cb, /* object passedType */)
        {
            if (File.Exists(c + "recent_IPs.txt"))
            {
                FileStream stream = new FileStream(c + "recent_IPs.txt", FileMode.Open);
                StreamReader reader = new StreamReader(stream);

                while (!reader.EndOfStream)
                {
                    string read = reader.ReadLine();
                    /* passedType t; */
                    if (/* passedType.TryParse(read, out t) */)
                    {
                        cb.Items.Add(read);
                    }
                }

                reader.Close();
                stream.Close();

                if (cb.Items.Count > 0)
                {
                    cb.SelectedIndex = 0;
                }
            }
        }
编辑:顺便说一下,在


您必须通过反射来实现这一点:

  • passedType
    更改为
    type
  • 使用
    Type.GetMethod
    Type.GetMethods
    查找正确的方法,注意该方法可能会重载
  • 调用该方法
或者,如果可能,更改方法以接受委托:

private void Input(string file, ComboBox cb, Func<string, bool> validator)

(etc)

阅读泛型(类型T)。使用Path.Combine()而不是字符串连接来创建最近的_IPs.txt文件的路径。@FrederikGheysels谢谢你,我不知道这个=)@FrederikGheysels我们可以对方法的参数做些什么吗,比如:string file=Path.Combine(c+文件)::我的意思是,我们可以在之前让文件参数为方法做好准备吗?谢谢。我不知道如何使用第一种方法,但我使用第二种方法。你能详细介绍一下1号的情况吗?哈克索洛默:你不明白哪一点?反思是一个大话题。好吧,我有第一行(Lol),我不知道第二行和第三行是关于什么的。。。我也不太了解反思
string c = Directory.GetCurrentDirectory();
private void Input(string file, ComboBox cb, Func<string, bool> validator)
Input(file, cb, text => { int dummy; return int.TryParse(text, out dummy); });