C# - Convert String to Class Object

后端 未结 3 1923
野的像风
野的像风 2021-01-19 10:47

I am working with someone else\'s code and trying to make some modifications. So what I\'m needing to do is take the following:

RemoteFileDP remoteFile = ne         


        
相关标签:
3条回答
  • 2021-01-19 11:13

    You're missing a constructor that takes a string as a parameter. Try your code with

    public RemoteFileDP(string locationDirectory)
    {
        // do stuff with locationDirectory to initialize RemoteFileDP appropriately
    }
    

    Of course, if you do that, why not just call the constructor directly?

    RemoteFileDP remoteFile = new RemoteFileDP(locationDirectory);
    
    0 讨论(0)
  • 2021-01-19 11:33

    If you don't wish to modify the source project that RemoteFileDP lives in (or can't) you could write an extension method such as below:

    public static RemoteFileDP ConvertToRemoteFileDP(this string location)
    {
        // Somehow create a RemoteFileDP object with your 
        // location string and return it
    }
    

    That way you could run the line of code you want:

    RemoteFileDP remoteFile = locationDirectory;
    

    With a slight modification as follows:

    RemoteFileDP remoteFile = locationDirectory.ConvertToRemoteFileDP();
    

    Would this allow you to solve your problem?

    0 讨论(0)
  • 2021-01-19 11:38

    Although I like the idea of a constructor accepting a string more, you could define an implicit or explicit conversion operator between RemoteFileDP and string:

     class RemoteFileDP
     {
          ....
    
          public static implicit operator RemoteFileDP(string locationDictionary)
          {
               //return a new and appropiately initialized RemoteFileDP object.
               //you could mix this solution with Anna's the following way:
               return new RemoteFileDP(locationDictionary);
          }
     }
    

    This way you could actually write:

     RemoteFileDP remoteFile = locationDirectory;
    

    or, if the conversion operator were to be explicit:

     RemoteFileDP remoteFile = (RemoteFileDP)locationDirectory;
    

    Still I insist, Anna Lear's solution is better as implicit or explicit conversion doesn't really seem to be the best fit for this kind of case. For instance, if the conversion can fail due to an invalid locationDictionary value then I wouldn't recommend this path. If the conversion is always succesful no matter what value locationDictionary is (barring null) then it could be a valid solution to your problem.

    I'm just putting it on the table as I think you might find it useful to know about explicit and implicit conversions in C#, in case you didn't already.

    0 讨论(0)
提交回复
热议问题