如何将构造函数中传递的字符串转换为Uri?

时间:2021-09-14 18:29:09

i have a piece of code in C#. I am using a string as parameter in the constructor to give the filepath then I want to convert it into Uri to interact with the rest of the code in a different class. How can i do that? Can anyone tell the syntax?

我在C#中有一段代码。我在构造函数中使用字符串作为参数来提供文件路径然后我想将其转换为Uri以与其他类中的其余代码进行交互。我怎样才能做到这一点?有谁能告诉语法?

    public string m_DTBook_FilePath;
    public DTBooktoXukConversion(string bookfile)
    {
        m_DTBook_FilePath = bookfile;
        Uri uri = new Uri(m_DTBook_FilePath);
    }      

Whats wrong in this syntax?

这个语法有什么问题?

1 个解决方案

#1


There's nothing wrong with that syntax. What's going wrong when you try it?

这种语法没有错。你尝试的时候出了什么问题?

Note that in the snippet you've given, you don't do anything with the Uri after constructing it - if the problem is that later you're trying to use m_DTBook_FilePath as a Uri, then you should actually have:

请注意,在你给出的代码片段中,在构造它之后你没有对Uri做任何事情 - 如果问题是你以后尝试使用m_DTBook_FilePath作为Uri,那么你应该实际拥有:

public Uri m_DTBook_FilePath;
public DTBooktoXukConversion(string bookfile)
{
    m_DTBook_FilePath = new Uri(bookfile);
}

(I would strongly recommend against having a public field in your real code, by the way.)

(顺便说一句,我强烈建议您不要在真实代码中使用公共字段。)

#1


There's nothing wrong with that syntax. What's going wrong when you try it?

这种语法没有错。你尝试的时候出了什么问题?

Note that in the snippet you've given, you don't do anything with the Uri after constructing it - if the problem is that later you're trying to use m_DTBook_FilePath as a Uri, then you should actually have:

请注意,在你给出的代码片段中,在构造它之后你没有对Uri做任何事情 - 如果问题是你以后尝试使用m_DTBook_FilePath作为Uri,那么你应该实际拥有:

public Uri m_DTBook_FilePath;
public DTBooktoXukConversion(string bookfile)
{
    m_DTBook_FilePath = new Uri(bookfile);
}

(I would strongly recommend against having a public field in your real code, by the way.)

(顺便说一句,我强烈建议您不要在真实代码中使用公共字段。)