C# - Convert String to Class Object

后端 未结 3 1924
野的像风
野的像风 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: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.

提交回复
热议问题